PostgreSQL + OpenJPA: exception when calling persist() - postgresql

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.

Related

Why is an Entity not persisted into database under TomEE 1.7 and EclipseLink 2.4.2?

As i have already worked JPA 2.1 with eclipselink 2.5.1 everything fine in that configuration. but due to some requirements i have came to JPA 2.0 with eclipselink 2.4.2 and now i am struggling to persist entities into database. as i am running my application while registering a user the data is getting stored some where and it is retrieved fine. but it is not getting persisted into database (MySql). Even i cant figure out the actual usage of JTA and RESOURCE LOCAL could someone help me here is my code
Create.java (register method)
public static int register(String first, String last, String email,
String date, String phone, String address, String pin, Login login) {
try {
System.out.println("registering persisting the entity");
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("FirstEE");
EntityManager manager = emf.createEntityManager();
manager.getTransaction().begin();
//
// Query query = manager
// .createQuery("select l from Truck l");
Login log = login;
System.out.println(log.getUsername() + "username"
+ log.getPassword() + "password");
User reg = new User();
reg.setLogin(log);
reg.setDate(date);
reg.setEmail(email);
reg.setFirst(first);
reg.setLast(last);
reg.setPhone(phone);
reg.setAddress(address);
reg.setPin(pin);
manager.flush();
manager.persist(reg);
manager.getTransaction().commit();
manager.close();
emf.close();
// FacesContext.getCurrentInstance().addMessage("reg:result",
// new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error Message",
// "Registered Successfully"));
FacesContext facesContext = FacesContext.getCurrentInstance();
FacesMessage facesMessage = new FacesMessage(
"Registered Successfully");
facesContext.addMessage(null, facesMessage);
System.out.println("after message global");
return 1;
} catch (Exception e) {
System.out.println("hai this is exception caught:" + e);
System.out.println("hai" + e.getMessage());
FacesContext.getCurrentInstance().addMessage(
"reg:result",
new FacesMessage("Something went wrong",
"\tSomething went wrong\t"));
// FacesContext facesContext = FacesContext.getCurrentInstance();
// FacesMessage facesMessage = new
// FacesMessage("Something went wrong");
// facesContext.addMessage(null, facesMessage);
}
return 0;
}
persistence.xml
<?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="FirstEE" transaction-type="RESOURCE_LOCAL">
<!-- <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> -->
<!-- <non-jta-data-source>FirstEE</non-jta-data-source> -->
<!-- <exclude-unlisted-classes>false</exclude-unlisted-classes> -->
<class>com.jason.Entity.User</class>
<class>com.jason.ManagedBean.Login</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/yash" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="eclipselink.logging.level" value="FINEST" />
<property name="eclipselink.ddl-generation" value="create-tables" />
</properties>
</persistence-unit>
</persistence>
error log:
<openjpa-2.4.0-r422266:1674604 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: This configuration disallows runtime optimization, but the following listed types were not enhanced at build time or at class load time with a javaagent: "
com.jason.Entity.User
com.jason.ManagedBean.Login".
at org.apache.openjpa.enhance.ManagedClassSubclasser.prepareUnenhancedClasses(ManagedClassSubclasser.java:115)
at org.apache.openjpa.kernel.AbstractBrokerFactory.loadPersistentTypes(AbstractBrokerFactory.java:311)
at org.apache.openjpa.kernel.AbstractBrokerFactory.initializeBroker(AbstractBrokerFactory.java:235)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:211)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:154)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:153)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:59)
at com.jason.service.GetUser.get(GetUser.java:45)
at com.jason.ManagedBean.Register.getAllUser(Register.java:199)
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 javax.el.BeanELResolver.invoke(BeanELResolver.java:183)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:161)
at org.apache.el.parser.AstValue.getValue(AstValue.java:173)
at org.apache.el.parser.AstEmpty.getValue(AstEmpty.java:46)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
at org.apache.webbeans.el22.WrappedValueExpression.getValue(WrappedValueExpression.java:70)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.UIComponentBase.isRendered(UIComponentBase.java:462)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1850)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:894)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:443)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at org.apache.myfaces.tomahawk.application.ResourceViewHandlerWrapper.renderView(ResourceViewHandlerWrapper.java:169)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at com.jason.Filter.Adminfilter.doFilter(Adminfilter.java:62)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
even i restart the eclipse IDE the values are still there. I am so confused. Is there any configuration issue existing here?
I got it i wanted others to know the exact problem. As i am using TomEE which is JavaEE server it is having openJPA as a default persistence provider.
If you want to use Other persistence providers we need to specify the <provider>your provider</provider> explicitly in persistence .xml
TomEE uses JTA as a default Transaction Manager. If you want to use RESOURCE_LOCAL you need to specify the transaction-type="RESOURCE_LOCAL" and also you need to specify the <non-jta-data-source>to be used by the application. otherwise the server will use JTA even though you specified the transaction type as RESOURCE_LOCAL
In order to configure JNDI Datasource refer this link.
Now the values are getting stored into the local database... remember you need to have all the libraries into your lib folder, also the jdbc connector into the server's lib folder so that that it would go well with the JNDI Datasource.
Have you tried to flush the em after persist?
Are you sure you are using eclipselink libraries? Maybe your server has it's own openjpa libraries and you have not override them.
If you look for similar problems on the net (like this, or this), people that have those problems are using openjpa.

Persistence unit for class issue

I am using Kundera with mongodb on a windows 7 box. I am trying to use int data type. But I am getting the following error.
Exception in thread "main" com.impetus.kundera.configure.schema.SchemaGenerationException: Persistence unit for class : int is not loaded
at com.impetus.kundera.configure.SchemaConfiguration.parseRelations(SchemaConfiguration.java:262)
at com.impetus.kundera.configure.SchemaConfiguration.configure(SchemaConfiguration.java:151)
at com.impetus.kundera.configure.ClientMetadataBuilder.buildClientFactoryMetadata(ClientMetadataBuilder.java:48)
at com.impetus.kundera.persistence.EntityManagerFactoryImpl.configureClientFactories(EntityManagerFactoryImpl.java:404)
at com.impetus.kundera.persistence.EntityManagerFactoryImpl.configure(EntityManagerFactoryImpl.java:157)
at com.impetus.kundera.persistence.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:131)
at com.impetus.kundera.KunderaPersistence.createEntityManagerFactory(KunderaPersistence.java:85)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at com.atomconnect.App.insertIntoMongo(App.java:37)
at com.atomconnect.App.main(App.java:53)
My entity object has the following fields
#Id
#Column(name="MESSAGE_ID")
private String messageId;
#Column(name = "SUBJECT")
private String subject;
#Column(name = "BODY")
private String body;
#Column(name = "zipcode")
private int zipcode;
#Embedded
private Contact from;
My persistence.xml looks like below
<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_1_0.xsd" version="2.0">
<persistence-unit name="ac">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<properties>
<property name="kundera.nodes" value="localhost" />
<property name="kundera.port" value="12345" />
<property name="kundera.keyspace" value="test" />
<property name="kundera.dialect" value="mongodb" />
<property name="kundera.client.lookup.class" value="com.impetus.client.mongodb.MongoDBClientFactory" />
<property name="" value="datastore_mongo.jar"/>
<!-- <property name="kundera.cache.provider.class" value="com.impetus.kundera.cache.ehcache.EhCacheProvider" />
<property name="kundera.cache.config.resource" value="/ehcache-test.xml" /> -->
</properties>
<jar-file>target/test.jar</jar-file>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
</persistence>
I wasted 2 days around this but not able to get the solution. Any help would be appreciated
Can you try removing
property name="" value="datastore_mongo.jar"
and share test.jar entities code ? Also , which version of Kundera are you using ?
I had a class for which I have declared the one to one mapping annotation for a int data type which was never used.
This should not cause any problem but the way kundera populates metadata via reflection is the issue.

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!

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