OpenJPA with Oracle - NullPointerException while creating the EntityManager - jpa

I am new to OpenJPA. When I tried to write a sample program with OpenJPA and Oracle, I am getting a NullPointerException while creating the EntityManager.
Sample program is
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("testjpa");
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
Customer customer = new Customer();
customer.setFirstName("Charles");
customer.setLastName("Dickens");
customer.setCustType("RETAIL");
customer.setStreet("10 Downing Street");
customer.setAppt("1");
customer.setCity("NewYork");
customer.setZipCode("12345");
em.persist(customer);
userTransaction.commit();
em.close();
entityManagerFactory.close();
}
persistence.xml is
<persistence-unit name="testjpa">
<provider>
org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>sample.jpa.entity.Customer</class>
<properties>
<property name="openjpa.jdbc.DBDictionary" value="oracle(DriverVendor=oracle)" />
<property name="openjpa.ConnectionURL" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="openjpa.ConnectionDriverName" value="oracle.jdbc.driver.OracleDriver" />
<property name="openjpa.ConnectionUserName" value="xxxxx" />
<property name="openjpa.ConnectionPassword" value="xxxxx" />
<property name="openjpa.Log" value="SQL=TRACE" />
</properties>
</persistence-unit>
Stacktrace is
Exception in thread "main" java.lang.NullPointerException
at sample.jpa.main.TestJPA.main(TestJPA.java:16)
This is happening at
EntityManager em = entityManagerFactory.createEntityManager();
Can anyone help me to resolve this?

Like Eelke told you already: You have to post the exact stack trace. There is no chance to start debugging this without the stack.
I also hope that his whitespace behind "Persistence" in your code snippet is just a typo:
EntityManagerFactory entityManagerFactory = Persistence .createEntityManagerFactory("testjpa");
Sebastian

Related

jpa 2.0 not injecting EntityManager

I have a simple implemenation of JPA 2.0 annotations that is not working. This is running in karaf 4.0.5 as a server. Below are listed the relevant excerpts from persistence.xml, blueprint.xml and the class. The exception is listed at the bottom.
The issue is that the EntityManager em is always null. I expected this to be injected by blueprint.
Can anyone point out where I've gone wrong?
Class
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
#Transactional
public class LookupMfgService implements ILookupMfgService {
private static Logger logger = LoggerFactory.getLogger(LookupMfgService.class);
#PersistenceContext(unitName = "pu_motordb3")
private EntityManager em;
#Override
public List<String> getPreferredMfgNames() throws BusinessException {
List<String> list = new ArrayList<>();
try {
// em is null here so NPE thrown
TypedQuery<String> q = em.createNamedQuery("listMfgPreferredNames", String.class);
list = q.getResultList();
} catch (Throwable t) {
logger.error("Error selecting list of manufacturers", t);
throw JpaExceptionFactory.createGeneralError(t, this.getClass().getName());
}
return list;
}
public void setEm(EntityManager entityManager) {
logger.debug(this.getClass().getName() + ".setEntityManager()");
logger.debug("setEntityManager called with " + (entityManager == null ? "null" : entityManager.toString()));
this.em = entityManager;
}
}
DataSource.xml
<blueprint default-activation="eager"
xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0
http://www.w3.org/2001/XMLSchema-instance http://www.w3.org/2001/XMLSchema-instance
http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0 http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0 ">
<bean id="dataSource" class="org.postgresql.ds.PGPoolingDataSource" destroy-method="close">
<property name="serverName" value="XXX"/>
<property name="user" value="XXX"/>
<property name="password" value="XXX"/>
<property name="dataSourceName" value="pgConnectionPool"/>
<property name="initialConnections" value="5"/>
<property name="maxConnections" value="50" />
</bean>
<service interface="javax.sql.DataSource" ref="dataSource">
<service-properties>
<entry key="osgi.jndi.service.name" value="MotorDB"/>
</service-properties>
</service>
</blueprint>
Blueprint.xml
<blueprint default-activation="eager"
xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ext="http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.0.0"
xmlns:tx="http://aries.apache.org/xmlns/transactions/v2.0.0" xmlns:jpa="http://aries.apache.org/xmlns/jpa/v2.0.0"
xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.0.0 http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.0.0
http://aries.apache.org/xmlns/transactions/v2.0.0 http://aries.apache.org/xmlns/transactions/v2.0.0
http://aries.apache.org/xmlns/jpa/v2.0.0 http://aries.apache.org/xmlns/jpa/v2.0.0
http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0 http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0">
<jpa:enable />
<tx:enable />
<service id="mfgLookupService" ref="mfgLookupEntityImpl" interface="ILookupMfgService"/>
</blueprint>
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="pu_motordb3" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=MotorDB)</jta-data-source>
Classes listed here
</persistence-unit>
</persistence>
Karaf log
2016-09-01 09:45:48,689 | INFO | PersistenceBundleTracker | 90 - org.apache.aries.jpa.container - 2.3.0 | Found persistence unit reference3 in bundle entity with provider org.apache.openjpa.persistence.PersistenceProviderImpl.
2016-09-01 09:45:48,695 | INFO | PersistenceBundleTracker | 90 - org.apache.aries.jpa.container - 2.3.0 | Found persistence unit pu_motordb3 in bundle entity with provider org.apache.openjpa.persistence.PersistenceProviderImpl.
2016-09-01 09:45:48,695 | INFO | PersistenceBundleTracker | 90 - org.apache.aries.jpa.container - 2.3.0 | Persistence units added for bundle com.easa.server.entity event 128
Exception
2016-08-31 18:42:49,286 | ERROR | nelWorkerThread0 | LookupMfgService | Error selecting list of manufacturers
java.lang.NullPointerException
at LookupMfgService.getPreferredMfgNames(LookupMfgService.java:93)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)[:1.8.0_91]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)[:1.8.0_91]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)[:1.8.0_91]
at java.lang.reflect.Method.invoke(Method.java:498)[:1.8.0_91]
at ch.ethz.iks.r_osgi.impl.ChannelEndpointImpl.handleMessage(ChannelEndpointImpl.java:1265)[69:ch.ethz.iks.r_osgi.remote:1.0.8.RC1_v20160823-2221]
at ch.ethz.iks.r_osgi.impl.ChannelEndpointImpl$2.run(ChannelEndpointImpl.java:315)[69:ch.ethz.iks.r_osgi.remote:1.0.8.RC1_v20160823-2221]
at ch.ethz.iks.r_osgi.impl.ChannelEndpointImpl$1.run(ChannelEndpointImpl.java:280)[69:ch.ethz.iks.r_osgi.remote:1.0.8.RC1_v20160823-2221]
Your datasource configuration appears to be missing. You are using osgi.jndi.service.name=MotorDB that is nowhere declared. So there is no service implementing javax.sql.DataSource
There has to be something similar to the following example which uses Oracle.
Change accordingly for other DBMS:
...
<bean id="dataSourceBeanMfgLookupService" class="oracle.jdbc.pool.OracleDataSource">
<property name="URL" value="???"/>
<property name="user" value="???"/>
<property name="password" value="???"/>
</bean>
<service id="dataSourceMfgLookupService" interface="javax.sql.DataSource" ref="dataSourceBeanMfgLookupService">
<service-properties>
<entry key="osgi.jndi.service.name" value="MotorDB" />
</service-properties>
</service>
...
Furthermore you may have to specify a persistence-provider in your persistence.xml. If you used hibernate with Oracle 10g it would look somehow like this:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" ...>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
...
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
...
Then you can link your datasource to your service:
<bean id="mfgLookupEntityImpl" class="LookupMfgService">
<jpa:context property="em" unitname="pu_motordb3" />
<tx:transaction method="*" value="Required" />
</bean>
If this still does not inject the EM provide a setter:
public void setEm(EntityManager entityManager) {
this.em = entityManager;
}
AFAIK there was/is a bug that property injection only worked if a setter was available.
The cause was an issue with karaf 4.0.5 and openjpa 2.4.1. It has been resolved in karaf 4.0.6

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.

Cannot create and close multiple EntityManagers in a SessionBean method

I'm trying to use OpenJPA Slice as a persistence mechanism for one of my classes inside a JBoss 4.0.5 (EJB 2.1) application server and I'm experiencing some problems.
In a J2SE setting the following code (create an EntityManager, use it, close it, create a new one, use it close it) works fine.
EntityManagerFactory factory = Persistence.createEntityManagerFactory("my_persistence_unit");
EntityManager em = factory.createEntityManager();
Query q = em.createQuery("select m from mytable m");
List result = q.getResultList();
// ... do something with result
em.close();
em = factory.createEntityManager();
q = em.createQuery("select m from myothertable m");
result = q.getResultList();
// ... do something with result
em.close();
But if I try to do the same thing in a StatelessSessionBean (again: EJB 2.1)
// the entity manager FACTORY is a static variable defined elsewhere
EntityManager em = FACTORY.createEntityManager();
Query q = em.createQuery("select m from mytable m");
List result = q.getResultList();
// ... do something with result
em.close();
em = FACTORY.createEntityManager();
q = em.createQuery("select m from myothertable m");
result = q.getResultList();
// ... do something with result
em.close();
... I get an exception on the second query execution:
<openjpa-1.0.1-r420667:592145 fatal user error> org.apache.openjpa.persistence.InvalidStateException: The context has been closed.
The same thing happens if I have only one query in my SessionBean method and I remote call it twice. The first call works just fine but the second call would throw the same exception.
It seems like all queries in the SessionBean are executed against the context of the first EntityManager ever created in the session bean.
If I don't call close() on the first EntityManager, everything works fine.
I'm puzzled why there's any interference between SessionBeans and JPA EntityManagers at all since JBoss 4 is so old that it shouldn't know anything about JPA.
This is the persistence.xml for the J2SE setup:
com.mycompany.MyEntity
<properties>
<property name="openjpa.BrokerFactory" value="slice"/>
<property name="openjpa.slice.Names" value="One,Two"/>
<property name="openjpa.slice.Master" value="One"/>
<property name="openjpa.slice.Lenient" value="true"/>
<property name="openjpa.slice.One.ConnectionURL" value="jdbc:mysql://localhost/jpa_test_1"/>
<property name="openjpa.slice.Two.ConnectionURL" value="jdbc:mysql://localhost/jpa_test_2"/>
<property name="openjpa.slice.DistributionPolicy" value="com.mycompany.RandomDistributionPolicy"/>
<property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionUserName" value="user"/>
<property name="openjpa.ConnectionPassword" value="password"/>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema"/>
<!-- -->
</properties>
</persistence-unit>
This is the persistence.xml for the JBoss setup:
<persistence-unit name="my_persistence_unit" transaction-type="RESOURCE_LOCAL">
<class>com.mycompany.MyEntity</class>
<properties>
<property name="openjpa.BrokerFactory" value="slice"/>
<property name="openjpa.slice.Names" value="One"/>
<property name="openjpa.slice.Master" value="One"/>
<property name="openjpa.slice.Lenient" value="true"/>
<property name="openjpa.ConnectionUserName" value="user"/>
<property name="openjpa.ConnectionPassword" value="password"/>
<property name="openjpa.slice.One.ConnectionURL" value="jdbc:mysql://localhost/jpa_test_1"/>
<property name="openjpa.slice.One.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
<property name="openjpa.slice.Two.ConnectionURL" value="jdbc:mysql://localhost/jpa_test_2"/>
<property name="openjpa.slice.Two.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
<property name="openjpa.slice.ThreadingPolicy" value="cached"/>
<property name="openjpa.slice.DistributionPolicy" value="com.mycompany.RandomDistributionPolicy"/>
<property name="openjpa.jdbc.DBDictionary" value="mysql"/>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema"/>
<property name="openjpa.Log" value="DefaultLevel=INFO, Runtime=TRACE, Tool=INFO, SQL=TRACE"/>
<property name="openjpa.jdbc.QuerySQLCache" value="false"/>
</properties>
</persistence-unit>

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>

Openejb with JPA - able to retrieve but cannot insert into database

I am using openejb as my standalone container to run my unit testcases, in all the test in all the tests i was able to retrieve the values but not able to insert or update. Even if i try entitymanager.merge(obj), it is selecting the value correctly but it is not updating it.
I am new to this , so please help me with this error
thanks in advance
my persistence.xml file
<persistence-unit name="test"
transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>java:/OracleDS</jta-data-source>
.....entity classes.....
<properties>
<property name="eclipselink.target-server" value="JBoss" />
<property name="eclipselink.target-database" value="Oracle" />
<property name="eclipselink.logging.level" value="FINE" />
<property name="eclipselink.logging.parameters" value="true" />
</properties>
</persistence-unit>
my dao method
tp.setname("van");
tp.settype("vehicle");
//entityManager.getTransaction().begin();
entityManager.merge(tp);
//entityManager.getTransaction().commit();
Do the followings for
Persist new entity:
Transport tp = new Transport();
tp.setname("van");
tp.settype("vehicle");
entityManager.getTransaction().begin();
entityManager.persist(tp);
entityManager.getTransaction().commit();
Update existing entity:
Query qry = entityManager.createQuery("Select t from
Transport t where t.type ='vechicle'");
List list = qry.getResultList();
//assume result return single entity
Transport tp = list.get(0);
tp.setInspectionDone(new Date()) ;
entityManager.getTransaction().begin();
entityManager.merge(tp);
entityManager.getTransaction().commit();
I think you need to ad #Transactional annotation in your class or method