JTA not rolling back when deleting cascade fails - jpa

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

Related

javax.persistence.PersistenceException: No Persistence provider for EntityManager named Eclipselink_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>
...

NamedQuery not found Hibernate4 Seam 2.2 JPA 2.0 and Jboss eap 6

I am receiving the Named Query not found error message on JBOSS EAP 6.3 server. I am using Hibernate4 Seam 2.2 JPA 2.0 and Jboss eap 6 in my application.
Caused by: java.lang.IllegalArgumentException: Named query not found: findOfficerByEmpIDFetchAssigners
at org.hibernate.ejb.AbstractEntityManagerImpl.createNamedQuery(AbstractEntityManagerImpl.java:601) [hibernate-entitymanager-4.2.14.SP1-redhat-1.jar:4.2.14.SP1-redhat-1]
at org.jboss.seam.persistence.EntityManagerProxy.createNamedQuery(EntityManagerProxy.java:46) [jboss-seam-2.2.0.GA.jar:2.2.0.GA]
at com.wachovia.apps.amaster.BatchProcessorBean.getLoggedInUser(BatchProcessorBean.java:68) [amaster-ejb-1.0.jar:]
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="AccountMaster">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/jdbc/AccountMaster</jta-data-source>
<properties>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider"/>
<property name="hibernate.cache.use_query_cache" value="false"/>
<property name="hibernate.show_sql" value="false"/>
<property name="jboss.entity.manager.jndi.name" value="java:jboss/AmasterEntityManager"/>
<property name="jboss.entity.manager.factory.jndi.name" value="java:jboss/AmasterEntityManagerFactory"/>
<property name="hibernate.default_schema" value="AMASTER"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.id.new_generator_mappings" value="false"/>
<property name="jboss.as.jpa.managed" value="false"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
<property name="jboss.as.jpa.adapterModule" value="org.jboss.as.jpa.hibernate:4"/>
<property name="jboss.as.jpa.adapterClass" value="org.jboss.as.jpa.hibernate4.HibernatePersistenceProviderAdaptor"/>
</properties>
My Entity class,
#Entity
#Table(name="OFFICER")
#NamedQueries({
#NamedQuery(name="findOfficerByEmployeeId",
query="from Officer where upper(employeeId)=upper(:id) order by employeeId"),
#NamedQuery(name="findOfficerByEmpIDFetchAssigners",
query="from Officer o left join fetch o.assigners ass where upper(o.employeeId) = :id")
})
public class Officer implements java.io.Serializable {
And Here is my Stateless bean class I am calling the NamedQuery,
#Stateless
#Name("batchProcessor")
#AutoCreate
#TransactionManagement(TransactionManagementType.BEAN)
public class BatchProcessorBean implements BatchProcessor, Serializable {
private static final long serialVersionUID = 395715959808111918L;
#SuppressWarnings("seam-unresolved-variable")
#In(value = "entityManager")
private EntityManager em;
public Officer getLoggedInUser(String employeeID) {
UserTransaction instance = Transaction.instance();
List<Officer> list = em.createNamedQuery("findOfficerByEmpIDFetchAssigners").setParameter("id", employeeID).getResultList();
I placed the persistence.xml in the under ejb/resources/META-INF folder. I have tried the previous posts regarding the NamedQuery Not found issue. That is not fixing my issue
Please help me to figure out the issue. Thanks
I have resolved the issue. I have added the the following class tag in persistence.xml to resolve the issue,
<class>com.wachovia.apps.amaster.orm.Officer</class>
The order of the tags are important in persistence.xml. In my case, this class tag must be added before the <properties> tag and after the <jta-data-source> tag.

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" />

Eclipselink with MongoDB java.lang.ClassCastException

I'm trying to configure a nosql persistence unit using Eclipselink and MongoDB but Im getting the following stack exception during deployment;
...
SEVERE: java.lang.ClassCastException: org.eclipse.persistence.nosql.adapters.mongo.MongoPlatform cannot be cast to org.eclipse.persistence.internal.databaseaccess.DatabasePlatform
at org.eclipse.persistence.sequencing.TableSequence.onConnect(TableSequence.java:168)
at org.eclipse.persistence.sequencing.Sequence.onConnect(Sequence.java:270)
at org.eclipse.persistence.internal.sequencing.SequencingManager.onConnectSequences(SequencingManager.java:927)
at org.eclipse.persistence.internal.sequencing.SequencingManager.onConnectInternal(SequencingManager.java:747)
at org.eclipse.persistence.internal.sequencing.SequencingManager.onConnect(SequencingManager.java:700)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.initializeSequencing(DatabaseSessionImpl.java:281)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.initializeDescriptors(DatabaseSessionImpl.java:629)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.initializeDescriptors(DatabaseSessionImpl.java:625)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.initializeDescriptors(DatabaseSessionImpl.java:565)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.postConnectDatasource(DatabaseSessionImpl.java:792)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.login(DatabaseSessionImpl.java:749)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:241)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:681)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:204)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:304)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:336)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:302)
at org.glassfish.persistence.jpa.JPADeployer$2.visitPUD(JPADeployer.java:451)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:510)
at org.glassfish.persistence.jpa.JPADeployer.iterateInitializedPUsAtApplicationPrepare(JPADeployer.java:492)
at org.glassfish.persistence.jpa.JPADeployer.event(JPADeployer.java:395)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:131)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:484)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:356)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandler.service(StaticHttpHandler.java:297)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:722)
The connection seems to be successfully established but then I get a java.lang.ClassCastException and the connection gets closed.
My PU in the persistence.xml looks like this:
<persistence-unit name="NoSQL_PU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-database" value="org.eclipse.persistence.nosql.adapters.mongo.MongoPlatform"/>
<property name="eclipselink.nosql.connection-spec" value="org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec"/>
<property name="eclipselink.nosql.property.mongo.port" value="27017"/>
<property name="eclipselink.nosql.property.mongo.host" value="localhost"/>
<property name="eclipselink.nosql.property.mongo.db" value="dev"/>
<property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</persistence-unit>
My NoSQL Entity class;
#NamedQueries({
#NamedQuery(name = "Comment.findAll", query = "SELECT e FROM Comment e"),
#NamedQuery(name = "Comment.findByPK", query = "SELECT e FROM Comment e WHERE e.id = :id"),})
#Entity
#NoSql(dataFormat = DataFormatType.MAPPED)
public class Comment implements Serializable {
// Serial-------------------------------------------------------------------
private static final long serialVersionUID = 1L;
// Variables----------------------------------------------------------------
#Id
#GeneratedValue
#Field(name="_id")
private String id;
#Basic
private Long created;
#Basic
private String commenterId;
#Basic
private String comment;
// Constructors-------------------------------------------------------------
// Getters------------------------------------------------------------------
// Setters------------------------------------------------------------------
}
Im using CTM so Im calling the PU in a stateless session bean;
#Stateless
public class TicketDAOImpl implements TicketDAO {
#PersistenceContext(unitName = "NoSQL_PU")
private EntityManager em;
}
Ive been following the eclipselink guide but I can't find anything pertaining to this.
The problem was with my persistence unit. By default ALL the Entity classes are included, So both my NoSQL and SQL entities were being passed to both the SQL and the NoSQL persistence units. The solution was just to specify the entities inside the persistence.xml persistence unit.
<persistence-unit name="Dastrax_NoSQL_PU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>declare_your_entity_1</class>
<class>declare_your_entity_2</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-database" value="org.eclipse.persistence.nosql.adapters.mongo.MongoPlatform"/>
<property name="eclipselink.nosql.connection-spec" value="org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec"/>
<property name="eclipselink.nosql.property.mongo.port" value="27017"/>
<property name="eclipselink.nosql.property.mongo.host" value="localhost"/>
<property name="eclipselink.nosql.property.mongo.db" value="dev"/>
<property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</persistence-unit>
I got the ClassCastException with EclipseLink 2.6.0.
Turned out it was a bug and it is fixed in 2.6.1
https://www.eclipse.org/eclipselink/downloads/milestones.php
Bug: https://www.eclipse.org/forums/index.php/t/1068464/
Note: At this moment 2.6.1 is not officially released but it worked great for me so far.
I think the correct answer would contain true in the exclude-unlisted-classes field. In other words, it would exclude the entity classes not belonging to the NoSQL JPA. Therefore, the persistence.xml should look as follows:
<persistence-unit name="Dastrax_NoSQL_PU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>declare_your_entity_1</class>
<class>declare_your_entity_2</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-database" value="org.eclipse.persistence.nosql.adapters.mongo.MongoPlatform"/>
<property name="eclipselink.nosql.connection-spec" value="org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec"/>
<property name="eclipselink.nosql.property.mongo.port" value="27017"/>
<property name="eclipselink.nosql.property.mongo.host" value="localhost"/>
<property name="eclipselink.nosql.property.mongo.db" value="dev"/>
<property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</persistence-unit>

WEB9031 - cannot store entity with sequence generated id

I am using glassfish, postgres and openjpa.
I only have one bean and first want to create a new intance and store it in DB. I created a new User-Object, filled it (except the id) and got - trying to persist - following exception:
Caused by: java.lang.IllegalStateException: WEB9031: WebappClassLoader unable to load resource [org.apache.openjpa.util.LongId], because it has not yet been started, or was already stopped
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1401)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
at org.myPlace.server.user.UserPDO.pcNewObjectIdInstance(UserPDO.java)
at org.apache.openjpa.enhance.PCRegistry.newObjectId(PCRegistry.java:142)
at org.apache.openjpa.meta.MetaDataRepository.processRegisteredClass(MetaDataRepository.java:1694)
at org.apache.openjpa.meta.MetaDataRepository.processRegisteredClasses(MetaDataRepository.java:1644)
... 128 more
WARNING: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for
servlet Faces Servlet threw exception
java.lang.IllegalStateException: WEB9031: WebappClassLoader unable to load resource
[org.apache.openjpa.util.LongId], because it has not yet been started, or was already stopped
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1401)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
at org.myPlace.server.user.UserPDO.pcNewObjectIdInstance(UserPDO.java)
at org.apache.openjpa.enhance.PCRegistry.newObjectId(PCRegistry.java:142)
at org.apache.openjpa.meta.MetaDataRepository.processRegisteredClass(MetaDataRepository.java:1694)
My bean looks like this:
#Entity
#Table(name="tbl_User")
public class UserPDO implements Serializable {
private long id;
private String username;
private String password;
public UserPDO() {}
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="user_seq_gen")
#SequenceGenerator(name="user_seq_gen", sequenceName="user_seq")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
... }
My persistence.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="myPlace" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>org.myPlace.server.user.UserPDO</class>
<properties>
<property name="openjpa.jdbc.DBDictionary" value="postgres"/>
<property name="openjpa.ConnectionDriverName" value="org.postgresql.Driver"/>
<property name="openjpa.ConnectionURL" value="jdbc:postgresql://localhost:5432/myPlace"/>
<property name="openjpa.ConnectionPassword" value="myPlace"/>
<property name="openjpa.ConnectionUserName" value="myPlace"/>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema"/>
<property name="openjpa.Log" value="File=/home/username/apache.log, DefaultLevel=ERROR, Tool=INFO, SQL=TRACE"/>
<property name="openjpa.DynamicEnhancementAgent" value="false" />
<property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" />
<property name="openjpa.DataCache" value="false"/>
<property name="openjpa.QueryCache" value="false"/>
</properties>
</persistence-unit>
The table is created correctly, so is the sequence. But when I want to create a new user object via
public <T> T create(T t) {
this.em.persist(t);
this.em.flush();
this.em.refresh(t);
return t;
}
I get the exception mentioned above. I found some questions/answers here that suggest that deactiving runtime-enhancement should do the trick. But it didn't work for me. My first idea was, that it might be a Classloader-Leak. I copied postgres-driver and openjpa-jars into the glassfish/lib-folder.
Can anybody help? Thanks!