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

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

Related

Spring-batch Entity Manager becomes null after init

I'm currently implementing a Spring-batch that reads and writes to files BUT also needs to do CRUD operations on a database.
I've tried to simply define an Entity manager in my xml configuration, and use it in my DAO class. However, right after the init, the EntityManager becomes null.
Can anyone help me with this ? (a solution or a link via something usable would be perfect).
My batchContext.xml
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${batch.datasource.driverClassName}"/>
<property name="url" value="${batch.datasource.url}"/>
<property name="username" value="${batch.datasource.username}"/>
<property name="password" value="${batch.datasource.password}"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="1800000"/>
<property name="numTestsPerEvictionRun" value="3"/>
<property name="minEvictableIdleTimeMillis" value="1800000"/>
</bean>
<bean id="entityManagerFactory" name="entTransactionMgr" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- <property name="persistenceXmlLocation" value="classpath:/META-INF/spring/persistence.xml" /> -->
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="packagesToScan" value="${jpa.scan.packages}"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<!-- Custom jpaDialect pour le deuxieme batch:job-repository-->
<property name="jpaDialect">
<bean class="fr.mma.soecm.batchfacade.util.CustomHibernateJpaDialect" />
</property>
<property name="jpaProperties">
<props>
<!-- multiple props here-->
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- mode="aspectj" -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<batch:job-repository id="jobRepository" data-source="dataSource" transaction-manager="transactionManager"/>
<!-- Jobs held separatelly -->
<import resource="batchContext-job.xml"/>
My DAO
#Repository("batchJobDao")
#Transactional
public class BatchJobDaoImpl implements BatchJobDao{
#PersistenceContext(unitName="persistenceUnit")
#Autowired
private EntityManager entityManager;
// #PersistenceContext(unitName="persistenceUnit", type=PersistenceContextType.EXTENDED)
// public void setEntityManager(EntityManager entityManager) {
// System.out.println("Setting Entity Manager :" + entityManager);
// this. entityManager = entityManager;
// }
#PostConstruct
public void init(){
if (entityManager == null){
System.out.println(" Entity Manager is null");
} else {
System.out.println(" Entity Manager is not null");
getAllJobExecutions();
}
}
private static final String RECHERCHER_JOB_EXECUTION = "Select bje from BatchJobExecution bje";
#SuppressWarnings("unchecked")
#Override
#Transactional("transactionManager")
public List<BatchJobExecution> getAllJobExecutions(){
// EntityManagerFactory emf=Persistence.createEntityManagerFactory("entTransactionMgr");
// EntityManager em=emf.createEntityManager();
Query query = entityManager.createQuery(RECHERCHER_JOB_EXECUTION, BatchJobExecution.class);
List<BatchJobExecution> executions = (List<BatchJobExecution>) query.getResultList();
System.out.println("EXES : " + executions);
return executions;
}
}
There is some code commented out because I've tried multiple aproaches (changing the persistence context type, recovering the entity manager "manually", having a persistence.xml file for the entityManager) without succes.
My output when running the job is (without all the extra lines..):
Entity Manager is not null
EXES : [fr.mma.soecm.batchfacade.domain.BatchJobExecution#10e6c33,...]
[BatchService] - Synchronous job launch
[AbstractStep] - Encountered an error executing the step
Caused by: java.lang.NullPointerException
And the null pointer, on debug, is throws by the EntityManager being null when I call the "createQuery" in my DAO.
Thanks for your help.
I'll keep searching on my end.. God Speed!
As mentioned in the comment above, my aparent problem was due to the fact that I was trying to call the Service or the DAO in the Constructor of the Step.
After moving the Service call in the "doRead()" method, I could perform all CRUD operations with the EntityManager.
Please let me know if anyone has questions about this/and how to make it work otherwise, as I've not found any explanation on the internet, since I've began searching last week.

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>

OpenJPA with Oracle - NullPointerException while creating the EntityManager

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