javax.persistence.PersistenceException: No Persistence provider for EntityManager named Eclipselink_JPA - jpa

I'm new to JPA and I'm pretty lost in this.
I created an enterprise project in netbeans to do some tests. Created this persistence unit with the wizard. I added it a JNDI connection that works proper and it's already tested:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="persistencia" transaction-type="JTA">
<jta-data-source>jdbc/nuevaConexion</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
Later, I created a sample entity with some test variables to see how this works:
#Entity
public class Entity1 implements Serializable {
private static long serialVersionUID = 1L;
private String nombre;
private int numero;
/**
* #return the serialVersionUID
*/
public static long getSerialVersionUID() {
return serialVersionUID;
}
/**
* #param aSerialVersionUID the serialVersionUID to set
*/
public static void setSerialVersionUID(long aSerialVersionUID) {
serialVersionUID = aSerialVersionUID;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
// setters & getters
Then, tried to make the service CreateEntity1 to give it a try, and try to create a new element on the DB by calling it:
public class CreateEntity1 {
public static void main( String[ ] args ) {
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager( );
entitymanager.getTransaction( ).begin( );
Entity1 ent = new Entity1( );
ent.setId(1);
ent.setNombre("Mi entidad");
ent.setNumero(123);
entitymanager.persist( ent );
entitymanager.getTransaction( ).commit( );
entitymanager.close( );
emfactory.close( );
}
}
... but it doesn't work. I get the following error:
Exception in thread "main" javax.persistence.PersistenceException: No
Persistence provider for EntityManager named Eclipselink_JPA at
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:85)
at
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at service.CreateEntity1.main(CreateEntity1.java:22)
C:\Users\hp\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53:
Java returned: 1 BUILD FAILED (total time: 0 seconds)
What am I doing wrong?
EDIT: I changed the name of the persistence provider to the good one, but now I'm getting a serious bunch of errors.
EDIT 2: Changed everything to Hibernate type. Still getting a huge error:
Exception in thread "main" Local Exception Stack: Exception
[EclipseLink-30009] (Eclipse Persistence Services -
2.6.1.v20150605-31e8258): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while trying to load
persistence unit at url:
file:/C:/Users/hp/Documents/NetBeansProjects/PruebasJ2EE/PruebasJ2EE-ejb/build/classes/
Internal Exception: Exception [EclipseLink-30004] (Eclipse Persistence
Services - 2.6.1.v20150605-31e8258):
org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while processing
persistence.xml from URL:
file:/C:/Users/hp/Documents/NetBeansProjects/PruebasJ2EE/PruebasJ2EE-ejb/build/classes/
Internal Exception: (1. El destino de la instrucción de procesamiento
que coincide con "[xX][mM][lL]" no está permitido.) at
org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionLoadingFromUrl(PersistenceUnitLoadingException.java:100)
at
org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processPersistenceArchive(PersistenceUnitProcessor.java:616)
at
org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.getPersistenceUnits(PersistenceUnitProcessor.java:500)
at
org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.findPersistenceUnitInfoInArchive(JPAInitializer.java:178)
at
org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.findPersistenceUnitInfoInArchives(JPAInitializer.java:160)
at
org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.findPersistenceUnitInfo(JPAInitializer.java:141)
at
org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:188)
at
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at service.CreateEntity1.main(CreateEntity1.java:22) Caused by:
Exception [EclipseLink-30004] (Eclipse Persistence Services -
2.6.1.v20150605-31e8258): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while processing
persistence.xml from URL:
file:/C:/Users/hp/Documents/NetBeansProjects/PruebasJ2EE/PruebasJ2EE-ejb/build/classes/
Internal Exception: (1. El destino de la instrucción de procesamiento
que coincide con "[xX][mM][lL]" no está permitido.) at
org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionProcessingPersistenceXML(PersistenceUnitLoadingException.java:118)
at
org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processPersistenceXML(PersistenceUnitProcessor.java:665)
at
org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processPersistenceArchive(PersistenceUnitProcessor.java:614)
... 8 more Caused by: (1. El destino de la instrucción de
procesamiento que coincide con "[xX][mM][lL]" no está permitido.) at
org.eclipse.persistence.internal.jpa.deployment.xml.parser.XMLExceptionHandler.error(XMLExceptionHandler.java:28)
at
org.eclipse.persistence.internal.jpa.deployment.xml.parser.XMLExceptionHandler.fatalError(XMLExceptionHandler.java:34)
at
com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:180)
at
com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:441)
at
com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at
com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1436)
at
com.sun.org.apache.xerces.internal.impl.XMLScanner.scanPIData(XMLScanner.java:723)
at
com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanPIData(XMLDocumentFragmentScannerImpl.java:1018)
at
com.sun.org.apache.xerces.internal.impl.XMLScanner.scanPI(XMLScanner.java:691)
at
com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:912)
at
com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
at
com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117)
at
com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at
com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
at
com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at
com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at
com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at
com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:649)
at
org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processPersistenceXML(PersistenceUnitProcessor.java:655)
... 9 more
C:\Users\hp\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53:
Java returned: 1 BUILD FAILED (total time: 0 seconds)

Look at my anwser at my anwser at Simplest working example of Spring Data JPA. To me it was simple enough. Hope it will be as simple to You.

You have missed <provider>... try to add it like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="persistencia" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
...

Related

PostgreSQL + OpenJPA: exception when calling persist()

I'm using OpenJPA 2.4.2 to access a PostgreSQL database from an ejb.
When calling persist (see the code below) I get the following exception:
<openjpa-2.4.2-r422266:1777108 fatal general error> org.apache.openjpa.persistence.PersistenceException: user lacks privilege or object not found: NEXTVAL {SELECT NEXTVAL('employee_id_seq')} [code=-5501, state=42501]
org.apache.openjpa.jdbc.sql.DBDictionary.narrow(DBDictionary.java:5003)
org.apache.openjpa.jdbc.sql.DBDictionary.newStoreException(DBDictionary.java:4963)
org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:133)
org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:107)
org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:59)
org.apache.openjpa.jdbc.kernel.AbstractJDBCSeq.next(AbstractJDBCSeq.java:63)
org.apache.openjpa.util.ImplHelper.generateValue(ImplHelper.java:159)
org.apache.openjpa.util.ImplHelper.generateFieldValue(ImplHelper.java:143)
org.apache.openjpa.jdbc.kernel.JDBCStoreManager.assignField(JDBCStoreManager.java:774)
org.apache.openjpa.util.ApplicationIds.assign(ApplicationIds.java:492)
org.apache.openjpa.util.ApplicationIds.assign(ApplicationIds.java:468)
org.apache.openjpa.jdbc.kernel.JDBCStoreManager.assignObjectId(JDBCStoreManager.java:758)
org.apache.openjpa.kernel.DelegatingStoreManager.assignObjectId(DelegatingStoreManager.java:135)
org.apache.openjpa.kernel.StateManagerImpl.assignObjectId(StateManagerImpl.java:595)
org.apache.openjpa.kernel.StateManagerImpl.preFlush(StateManagerImpl.java:3051)
org.apache.openjpa.kernel.PNewState.beforeFlush(PNewState.java:44)
org.apache.openjpa.kernel.StateManagerImpl.beforeFlush(StateManagerImpl.java:1072)
org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2143)
org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:2103)
org.apache.openjpa.kernel.BrokerImpl.beforeCompletion(BrokerImpl.java:2021)
org.apache.geronimo.transaction.manager.TransactionImpl.beforeCompletion(TransactionImpl.java:527)
org.apache.geronimo.transaction.manager.TransactionImpl.beforeCompletion(TransactionImpl.java:512)
org.apache.geronimo.transaction.manager.TransactionImpl.beforePrepare(TransactionImpl.java:413)
org.apache.geronimo.transaction.manager.TransactionImpl.commit(TransactionImpl.java:262)
org.apache.geronimo.transaction.manager.TransactionManagerImpl.commit(TransactionManagerImpl.java:252)
org.apache.openejb.core.transaction.JtaTransactionPolicy.completeTransaction(JtaTransactionPolicy.java:331)
org.apache.openejb.core.transaction.TxRequired.commit(TxRequired.java:76)
org.apache.openejb.cdi.transactional.InterceptorBase.intercept(InterceptorBase.java:68)
org.apache.openejb.cdi.transactional.RequiredInterceptor.intercept(RequiredInterceptor.java:35)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.webbeans.component.InterceptorBean.intercept(InterceptorBean.java:136)
org.apache.webbeans.intercept.InterceptorInvocationContext.proceed(InterceptorInvocationContext.java:63)
org.apache.webbeans.intercept.DefaultInterceptorHandler.invoke(DefaultInterceptorHandler.java:139)
com.virtualpairprogrammers.staffmanagement.dataaccess.EmployeeDataAccessImplementation$$OwbInterceptProxy0.insert(com/virtualpairprogrammers/staffmanagement/dataaccess/EmployeeDataAccessImplementation.java)
com.virtualpairprogrammers.staffmanagement.EmployeeManagementImplementation.registerEmployee(EmployeeManagementImplementation.java:22)
com.virtualpairprogrammers.backingbeans.AddEmployeeBean.AddEmployee(AddEmployeeBean.java:45)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.el.parser.AstValue.invoke(AstValue.java:247)
org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
org.apache.webbeans.el22.WrappedMethodExpression.invoke(WrappedMethodExpression.java:52)
org.apache.myfaces.view.facelets.el.ContextAwareTagMethodExpression.invoke(ContextAwareTagMethodExpression.java:96)
org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:74)
javax.faces.component.UICommand.broadcast(UICommand.java:120)
javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:1174)
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:365)
javax.faces.component.UIViewRoot._process(UIViewRoot.java:1660)
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:864)
org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:42)
org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:196)
org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:143)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:198)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
Here is how I call persist and define the persistence context:
#Transactional
public class EmployeeDataAccessImplementation implements EmployeeDataAccess
{
#PersistenceContext(unitName = "EmployeeDB")
private EntityManager em;
...
public void insert(Employee newEmployee) {
em.persist(newEmployee);
}
}
Here is how I configure the persistence unit EmployeeDB in persistence.xml:
<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="EmployeeDB">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>com.virtualpairprogrammers.staffmanagement.domain.Employee</class>
<properties>
<property name="persistence.openjpa.ConnectionDriverName" value="org.postgresql.Driver"/>
<property name="persistence.openjpa.ConnectionURL" value="jdbc:postgresql://localhost:5432/EmployeeDB"/>
<property name="persistence.openjpa.ConnectionUserName" value="postgres"/>
<property name="persistence.openjpa.ConnectionPassword" value="test"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
<property name="openjpa.jdbc.DBDictionary" value="postgres(SchemaCase=lower)"/>
</properties>
</persistence-unit>
Finally, here is how I map the class Employee to the database table Employee:
#Entity(name="employee")
public class Employee {
#Id
#GeneratedValue (strategy = GenerationType.SEQUENCE, generator="employee_gen")
#SequenceGenerator (name="employee_gen", sequenceName="employee_id_seq", allocationSize=1)
#Getter #Setter
private Long id;
...
public Employee() {}
}
I've created the sequence employee_id_seq using the following SQL command:
create sequence employee_id_seq;
Just in case I've changed the owner and granted all the priviledges on employee_id_seq to postgres:
alter sequence public.employee_id_seq OWNER TO postgres;
GRANT USAGE, SELECT ON SEQUENCE employee_id_seq TO postgres;
I will appreciate your help.

EntityManager in JNDI

I need to use different databases in the same Web application, so I can't use a persistent.xml to define the target database. The database changes with the client which is connected.
I found this :
public EntityManager getEntityManager() {
if (em == null}
try{
em = (EntityManager)(new InitialContext())
.lookup("java:comp/ejb/EntityManager");
} catch (Exception e){};
}
return em;
}
at this URL : http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI
My question is now : how recording a EntityManager or a Persistence Unit in the JNDI of GlassFish ?
Suppose that my persistence.xml is:
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="ctx-vendor" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
</persistence-unit>
</persistence>
We have two use case:
WAR application WEB-INF/web.xml file:
<persistence-context-ref>
<description>JNDI for lookup EntityManager</description>
<persistence-context-ref-name>persistence/ctx-vendor</persistence-context-ref-name>
<persistence-unit-name>ctx-vendor</persistence-unit-name>
<persistence-context-type>Transaction</persistence-context-type>
</persistence-context-ref>
EAR application META-INF/application.xml file:
<application xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/application_7.xsd"
version="7">
<description>My Vendor System</description>
<display-name>vendor-ear</display-name>
<module>
<web>
<web-uri>vendor-rest.war</web-uri>
<context-root>/vendor-rest</context-root>
</web>
</module>
<module>
<ejb>vendor-service.jar</ejb>
</module>
<library-directory>lib</library-directory>
<persistence-context-ref>
<description>JNDI for lookup EntityManager</description>
<persistence-context-ref-name>persistence/ctx-vendor</persistence-context-ref-name>
<persistence-unit-name>ctx-vendor</persistence-unit-name>
<persistence-context-type>Transaction</persistence-context-type>
</persistence-context-ref>
</application>
Stateless Session Bean
#PersistenceContext(name = "persistence/ctx-vendor", unitName = "ctx-vendor")
public class BaseFacade
{ }
#Stateless
#Local(CatalogFacade.class)
public class CatalogFacadeImpl extends BaseFacade implements CatalogFacade
{
}
Tested in Glassfish 4.1

Table/View does not exist in JavaEE web app deployed on Glassfish

I tried to deploy a JavaEE Web app with JPA persistence on a Glassfish server I installed on an Amazon EC2 instance. Everything worked fine for the deployment and for web pages rendering in my browser, but when I try to use persistence the result is the error "Table/View 'ATHLETE' does not exist'.
This is the first time I try to develop a web app with JPA and I'm trying to create a skeleton to use in the future for we app, but I think I'm missing a fundamental part. Also, using #GeneratedValue for the #Id I get a SEQUENCE table missing error. I'm afraid the two problems are related
The Athlete.java
package com.storassa.javaee.scuolesci;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
#Entity
#NamedQuery(name = "findAllAthletes", query = "SELECT b FROM Athlete b")
public class Athlete {
static int idRaw; // I use this to avoid the #GeneratedValue issue
#Id
int id;
String name, surname;
int birth;
public Athlete () {
idRaw++;
id = idRaw;
}
<getters and setters>
}
The AthleteEjb.java
package com.storassa.javaee.scuolesci;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Startup;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.annotation.sql.*;
#LocalBean
#Stateless
public class AthleteEJB {
#PersistenceContext(unitName="scuoleSciPU")
private EntityManager em;
public List<Athlete> findAthlete() {
Query query = em.createNamedQuery("findAllAthletes");
return query.getResultList();
}
public Athlete createAthlete(Athlete athlete) {
em.persist(athlete);
return athlete;
}
}
The persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="2.1">
<persistence-unit name="scuoleSciPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.storassa.javaee.scuolesci.Athlete</class>
<properties>
<property name="eclipselink.target-database" value="DERBY" />
<property name="eclipselink.jdbc.driver"
value="org.apache.derby.jdbc.ClientDriver" />
<property name="eclipselink.jdbc.url"
value="jdbc:derby://localhost:1527;create=true" />
<property name="eclipselink.jdbc.user" value="APP" />
<property name="eclipselink.jdbc.password" value="APP" />
<property name="eclipselink.ddl-generation" value=" drop-and-create-tables" />
<property name="eclipselink.logging.level" value="INFO" />
<property name="eclipselink.deploy-on-startup" value="true" />
</properties>
</persistence-unit>
</persistence>
The error returned on the browser
type Exception report
message Internal Server Error
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: javax.ejb.EJBException: Transaction aborted
root cause
javax.faces.el.EvaluationException: javax.ejb.EJBException: Transaction aborted
root cause
javax.ejb.EJBException: Transaction aborted
root cause
javax.transaction.RollbackException: Transaction marked for rollback.
root cause
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Table/View 'ATHLETE' does not exist.
Error Code: -20001
Call: INSERT INTO ATHLETE (ID, BIRTH, NAME, SURNAME) VALUES (?, ?, ?, ?)
bind => [4 parameters bound]
Query: InsertObjectQuery(com.storassa.javaee.scuolesci.Athlete#65fd5648)
root cause
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Table/View 'ATHLETE' does not exist.
Error Code: -20001
Call: INSERT INTO ATHLETE (ID, BIRTH, NAME, SURNAME) VALUES (?, ?, ?, ?)
bind => [4 parameters bound]
Query: InsertObjectQuery(com.storassa.javaee.scuolesci.Athlete#65fd5648)
root cause
java.sql.SQLSyntaxErrorException: Table/View 'ATHLETE' does not exist.
root cause
org.apache.derby.client.am.SqlException: Table/View 'ATHLETE' does not exist.
I don't provide web-related resource/classes as I don't think they can be useful. In case let me know.
Should the table ATHLETE be created due to the #Entity annotation and the ?
I guess the problem is related to leading space in eclipselink.ddl-generation value. In other words try to replace:
<property name="eclipselink.ddl-generation" value=" drop-and-create-tables" />
with
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />

JTA not rolling back when deleting cascade fails

Using: Glassfish 3.1.2, EclipseLink.
I have the following three-classes JPA model:
#Entity public class Customer implements Serializable {
#Id private Integer id;
#OneToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}, orphanRemoval=true)
private Person person;
[...]
#Entity public class Person implements Serializable {
#Id private Integer id;
[...]
#Entity public class Request implements Serializable {
#Id private Integer id;
#ManyToOne private Person person;
I try to remove a customer with the following strategy (using CMT):
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="MyPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="database"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="eclipselink.logging.logger" value="DefaultLogger"/>
<property name="eclipselink.logging.timestamp" value="true"/>
<property name="eclipselink.logging.session" value="false"/>
<property name="eclipselink.logging.thread" value="false"/>
</properties>
</persistence-unit>
[...]
#PersistenceContext(unitName="MyPU")
private EntityManager entityManager;
#Resource private SessionContext context;
[...]
public void delete(Entity object) {
try{
object = this.getEntityManager().merge(object);
this.getEntityManager().remove(object);
} catch (Exception e){
this.context.setRollbackOnly();
}
}
When the Customer object is attached to a Person object that is attached to a Request, the delete cascade of Person fails causing the transaction to rollback, but the Customer is deleted from the database. I receive the following error:
INFO: [EL Fine]: 2012-12-28 10:53:38.1--Connection(27132168)--DELETE FROM CUSTOMER WHERE (ID = ?)
bind => [97]
INFO: [EL Fine]: 2012-12-28 10:53:38.125--Connection(27132168)--DELETE FROM PERSON WHERE (ID = ?)
bind => [111]
INFO: [EL Fine]: 2012-12-28 10:53:38.126--SELECT 1
WARNING: DTX5014: Caught exception in beforeCompletion() callback:
Local Exception Stack:
INFO: [EL Warning]: 2012-12-28 10:53:38.127--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERRO: atualização ou exclusão em tabela "person" viola restrição de chave estrangeira "fk_request_person_id" em "request"
Detalhe: Chave (id)=(111) ainda é referenciada pela tabela "request".
Error Code: 0
Call: DELETE FROM PERSON WHERE (ID = ?)
bind => [111]
Query: DeleteObjectQuery(111)
[...]
SEVERE: javax.ejb.EJBException: Transaction aborted
[...]
So, how can i cancel the customer removal when the cascade deletion fails?
There are two things that possible may go wrong here.
The transaction boundaries are not correctly specified
Maybe due to this, your application server does not issue the BEGIN statement correctly. This would explain that Postgres has a problem, while Oracle does not (it implicitly starts a transaction). Make sure your service methods wear the correct annotations. If everything is fine, maybe
There is a problem with your datasource.
Is it a JTA compatible datasource? Does it use the correct driver for Postgres? Please post your config so that we can check out.
I found an interesting link that may help you as well. It is about Postgres staying in autocommit mode (although when using Spring):
http://archives.postgresql.org/pgsql-jdbc/2007-07/msg00115.php

GWT RCP - SerializationException

Started a new project from scratch, converted to JPA, my persistence provider is EclipseLink, added the necessary libraries (eclipselink.jar, eclipselink.jar, javax.persistence, mysql-connector-java-5.1). Tested the connection, ping ok. Then created a new package New > JPA > Entities from Tables > Selected all Entities and Key generator > Identity.
GestorIpca.java
GestorIpcaService.util.getInstance().getLista(new AsyncCallback<ArrayList<Docente>>() {
#Override
public void onFailure(Throwable caught) {
Window.alert("Erro na Ligacao efectuada");
caught.getStackTrace();
}
#Override
public void onSuccess(ArrayList<Docente> result) {
Window.alert("Ligacao efectuada com sucesso:" + result.size());
}
});
GestorIpcaService
#RemoteServiceRelativePath("greet")
public interface GestorIpcaService extends RemoteService {
String greetServer(String name) throws IllegalArgumentException;
public static class util{
public static GestorIpcaServiceAsync instance;
public static GestorIpcaServiceAsync getInstance(){
if(instance == null){
instance = GWT.create(GestorIpcaService.class);
}
return instance;
}
}
public ArrayList<Docente> getLista() throws IllegalArgumentException;
}
GestorIpcaServiceAsync
public interface GestorIpcaServiceAsync {
void greetServer(String input, AsyncCallback<String> callback)
throws IllegalArgumentException;
void getLista(AsyncCallback<ArrayList<Docente>> callback);
}
GestorIpcaServiceImpl
#SuppressWarnings("serial")
public class GestorIpcaServiceImpl extends RemoteServiceServlet implements
GestorIpcaService {
public ArrayList<Docente> getLista() throws IllegalArgumentException {
//Criamos um EntityManager
EntityManager em = JpaUtil.getEntityManagerFactory().createEntityManager();
//Criamos a consulta
String consulta = "SELECT r from Docente r";
//Executamos a consulta
Query q = em.createQuery(consulta);
ArrayList<Docente> lista = new ArrayList<Docente>(q.getResultList());
return lista;
}
/* public static void main(String args[]){
GestorIpcaServiceImpl serviceImpl = new GestorIpcaServiceImpl();
for (Docente docente : serviceImpl.getLista()){
System.out.println("nome: " + docente.getNome());
}
}
*/
In this file i tried to run as > Java Application and in Console showed me 2 records.
Package com.GestorIpca.factory
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class JpaUtil {
private static final EntityManagerFactory emf;
//Método estático
static{
//BLoco try
try
{
//Criação de EntityManagerFactory
emf = Persistence.createEntityManagerFactory("GestorIpca");
}catch (Throwable e){
//Controlar as excepções
System.err.println("A criação de SessionFactory falhou" + e);
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
public static EntityManagerFactory getEntityManagerFactory(){
return emf;
}
}
My persistence.xml was created automatically. Placed inside META-INF
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="GestorIpca">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.GestorIpca.shared.Ano</class>
<class>com.GestorIpca.shared.Categoria</class>
<class>com.GestorIpca.shared.Curso</class>
<class>com.GestorIpca.shared.Disciplina</class>
<class>com.GestorIpca.shared.Disponibilidade</class>
<class>com.GestorIpca.shared.Docente</class>
<class>com.GestorIpca.shared.Sala</class>
<class>com.GestorIpca.shared.Semestre</class>
<class>com.GestorIpca.shared.TipoCurso</class>
<class>com.GestorIpca.shared.Turma</class>
<class>com.GestorIpca.shared.User</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/timetable"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="k771u3"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>
Last step > Run as > Web Application
Error > Could not connect to database and print a stack trace in Eclipse Console
[EL Info]: 2011-05-09 10:03:08.78--ServerSession(8068087)--EclipseLink, version: Eclipse Persistence Services - 2.2.0.v20110202-r8913
[EL Info]: 2011-05-09 10:03:09.297--ServerSession(8068087)--file:/C:/Users/Martinho/WorkSpace/GestorIpca/war/WEB-INF/classes/_GestorIpca login successful
Starting Jetty on port 8888
[WARN] Exception while dispatching incoming RPC call
com.google.gwt.user.client.rpc.SerializationException: java.lang.reflect.InvocationTargetException
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeWithCustomSerializer(ServerSerializationStreamWriter.java:764)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeImpl(ServerSerializationStreamWriter.java:727)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:616)
at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:126)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter$ValueWriter$8.write(ServerSerializationStreamWriter.java:152)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeValue(ServerSerializationStreamWriter.java:534)
at com.google.gwt.user.server.rpc.RPC.encodeResponse(RPC.java:616)
at com.google.gwt.user.server.rpc.RPC.encodeResponseForSuccess(RPC.java:474)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:571)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeWithCustomSerializer(ServerSerializationStreamWriter.java:746)
... 30 more
Caused by: com.google.gwt.user.client.rpc.SerializationException: Type 'org.eclipse.persistence.indirection.IndirectSet' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = {IndirectSet: not instantiated}
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:614)
at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:126)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter$ValueWriter$8.write(ServerSerializationStreamWriter.java:152)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeValue(ServerSerializationStreamWriter.java:534)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeClass(ServerSerializationStreamWriter.java:704)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeImpl(ServerSerializationStreamWriter.java:734)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:616)
at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:126)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter$ValueWriter$8.write(ServerSerializationStreamWriter.java:152)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeValue(ServerSerializationStreamWriter.java:534)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeClass(ServerSerializationStreamWriter.java:704)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeImpl(ServerSerializationStreamWriter.java:734)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:616)
at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:126)
at com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase.serialize(Collection_CustomFieldSerializerBase.java:45)
at com.google.gwt.user.client.rpc.core.java.util.ArrayList_CustomFieldSerializer.serialize(ArrayList_CustomFieldSerializer.java:38)
... 35 more
[ERROR] 500 - POST /gestoripca/greet (127.0.0.1) 57 bytes
Request headers
Host: 127.0.0.1:8888
Connection: keep-alive
Referer: http://127.0.0.1:8888/GestorIpca.html?gwt.codesvr=127.0.0.1:9997
Content-Length: 132
Origin: http://127.0.0.1:8888
X-GWT-Module-Base: http://127.0.0.1:8888/gestoripca/
X-GWT-Permutation: HostedMode
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.30 Safari/534.30
Content-Type: text/x-gwt-rpc; charset=UTF-8
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pt-PT,pt;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Response headers
Content-Type: text/plain
Note: I changed in package com.GestorIpca.shared all my classes generated from tables
public class Ano implements Serializable
to
public class Ano implements IsSerializable
changed also my GestorIpca.gwt.xml and added this lines in end
<extend-configuration-property name="rpc.blacklist" value="com.google.gwt.user.client.ui.*Collection"/>
<extend-configuration-property name="rpc.blacklist" value="-.*List"/>
<extend-configuration-property name="rpc.blacklist" value="-.*Map"/>
<extend-configuration-property name="rpc.blacklist" value="-.*Collection"/>
<extend-configuration-property name="rpc.blacklist" value="+java.util.HashMap"/>
<extend-configuration-property name="rpc.blacklist" value="+java.util.LinkedHashMap"/>
<extend-configuration-property name="rpc.blacklist" value="+java.util.ArrayList"/>
What am i missing?
I depends on how your entities were defined. Maybe there are connections that GWT RPC doesn´t like. in this case i´d suggest create DTO´s or implement RequestFactory
Without knowing what your entities look like I would guess from the exception that the reason is probably how your entities get enhanced by your persistence provider:
What this means for GWT RPC is that by the time the object is ready to be transferred over the wire, it actually isn't the same object that the compiler thought was going to be transferred, so when trying to deserialize, the GWT RPC mechanism no longer knows what the type is and refuses to deserialize it.
Cited from: http://code.google.com/intl/de-DE/webtoolkit/articles/using_gwt_with_hibernate.html
That article also suggests how to create DTOs to solve this problem.
I know this is a very old question, but I ran into this exact issue tonight.
GWT Serialization doesn't seem to like java.util.Set. I almost feel like it was confusing java.util.Set with org.eclipse.persistence.indirection.IndirectSet.
Once I switched Set to ArrayList, the error went away.