When I try to run the Unit test for this DAO class, I am getting NullPointerException at getById return statement. I know that the class does not initialize the EntityManager, but I don’t understand why? - I can’t tell whether my persistence.xml configuration is wrong or the DB credentials are incorrect.
I saw two or more StackOverflow threads but had had little luck. I am using Intellij IDE.
package com.beetlehand.model.dao;
import com.beetlehand.model.AttributeEntity;
import org.apache.commons.lang.StringUtils;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
#Stateless
public class AttributeDao extends AbstractDao<AttributeEntity> {
#PersistenceContext(unitName = "NewPersistenceUnit")
protected EntityManager entityManager;
public AttributeEntity getById(Long id) {
if(id == null) return null;
return entityManager.find(AttributeEntity.class, id);
}
/*** more code ***/
}
Persistence configuration file
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="NewPersistenceUnit">
<class>com.beetlehand.model.AttributeEntity</class>
<class>com.beetlehand.model.AttributeValueEntity</class>
<class>com.beetlehand.model.AuditEntity</class>
<class>com.beetlehand.model.CategoryEntity</class>
<class>com.beetlehand.model.CustomerEntity</class>
<class>com.beetlehand.model.DepartmentEntity</class>
<class>com.beetlehand.model.OrderDetailEntity</class>
<class>com.beetlehand.model.OrdersEntity</class>
<class>com.beetlehand.model.ProductEntity</class>
<class>com.beetlehand.model.ProductAttributeEntity</class>
<class>com.beetlehand.model.ProductCategoryEntity</class>
<class>com.beetlehand.model.ReviewEntity</class>
<class>com.beetlehand.model.ShippingEntity</class>
<class>com.beetlehand.model.ShippingRegionEntity</class>
<class>com.beetlehand.model.ShoppingCartEntity</class>
<class>com.beetlehand.model.TaxEntity</class>
<properties>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/beetlehand"/>
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/beetlehand"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionURL" value="jdbc:mysql://localhost:3306/beetlehand"/>
<property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.jdbc.url" value="jdbc:mysql://localhost:3306/beetlehand"/>
<property name="eclipselink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="username"/>
<property name="hibernate.connection.password" value="password"/>
</properties>
</persistence-unit>
</persistence>
You need to mock the entityManager then you need to do stub for entityManager.find() as shown below.
#Mock // Mocking enitt
private EntityManager entityManager;
public AttributeEntity entity = new AttributeEntity();
// Stubbing for entityManager.find()
Mockito.when(entityManager.find(Mockito.any(AttributeEntity.class), Mockito.any())).thenReturn(entity);
I am trying to call JPA from a rest web service. but it throws me
org.hibernate.integrator.spi.Integrator: Provider org.hibernate.envers.event.EnversIntegrator not a subtype at org.apache.cxf.service.invoker.AbstractInvoker.createFault(AbstractInvoker.java:170) at
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:136) at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:204) at
org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:101) at
org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:68) at org.apache.cxf.interceptor.ServiceInvokerInterceptor
I have used maven 4, JPA 2.1, CDI.
My code:
JPA part:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultMainUnit", null);
EntityManager entityManager = entityManagerFactory.createEntityManager();
Persistence.generateSchema("defaultMainUnit", null);
Query master Query = entityManager
.createNamedQuery("master.findAll");
List<Master > masterList = masterQuery.getResultList();
for(Master master : masterList){
System.out.println("Master id: "+master .getMaster TrackingId());
}
entityManager.clear();
entityManager.close();
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="defaultMainUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>core.Master</class>
<class>core.Child</class>
<properties>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" />
<property name="hibernate.connection.url" value="jdbc:hsqldb:mem:defaultDB" />
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.connection.release_mode" value="after_statement"/>
<!-- insert data using sql file -->
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.schema-generation.create-source" value="metadata"/>
<property name="javax.persistence.schema-generation.drop-source" value="metadata"/>
<property name="javax.persistence.sql-load-script-source" value="mcb-test-import.sql"/>
</properties>
</persistence-unit>
Restservice:
package restcdi.rest;
#Path("/")
public class GreetREST {
#Inject
private EnglishGreet greet;
#GET
#Path("/greet")
#Produces(MediaType.TEXT_PLAIN)
public String greet() {
return greet.greet();
}
#GET
#Path("/master")
#Produces(MediaType.APPLICATION_JSON)
public List master() throws FileNotFoundException, IOException{
CheckJPAProperties check = new CheckJPAProperties();
List masterList = check.runMe();
return masterList;
}
}
in the above code, runMe() returns all the masters in database using JPA code above. when i run the JPA code without a rest service in main it runs fine and returns everything. I am not sure what I am missing. I tried including the hibernate-envers dependency in pom.xml but it still throws the same error.
please help.
ps: just in case this is needed i am including my applicationConfig
package restcdi.rest;
import java.util.Set;
import javax.ws.rs.core.Application;
#javax.ws.rs.ApplicationPath("rest")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
resources.add(GreetREST.class);
return resources;
}
}
getting this error in eclipselink JPA example. I am trying to set up a simple JPA class. It complains about the xml document not being well formed, but I don't see any problems. please let me know of any pointers. thanks!
Main class is:
package de.vogella.jpa.simple.main;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import de.vogella.jpa.simple.model.Todo;
public class Main {
private static final String PERSISTENCE_UNIT_NAME = "todos";
private static EntityManagerFactory factory;
public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// read the existing entries and write to console
Query q = em.createQuery("select t from Todo t");
List<Todo> todoList = q.getResultList();
for (Todo todo : todoList) {
System.out.println(todo);
}
System.out.println("Size: " + todoList.size());
// create new todo
em.getTransaction().begin();
Todo todo = new Todo();
todo.setSummary("This is a test");
todo.setDescription("This is a test");
em.persist(todo);
em.getTransaction().commit();
em.close();
}
}
here is persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="todos" transaction-type="RESOURCE_LOCAL">
<class>de.vogella.jpa.simple.model.Todo</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:derby:/home/vogella/databases/simpleDb;create=true" />
<property name="javax.persistence.jdbc.user" value="test" />
<property name="javax.persistence.jdbc.password" value="test" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
</properties>
</persistence-unit>
</persistence>
The error is the following:
Exception in thread "main" Local Exception Stack:
Exception [EclipseLink-30009] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while trying to load persistence unit at url: file:/C:/paul/oneView/java/de.vogella.jpa.simple/build/eclipse/
Internal Exception: Exception [EclipseLink-30004] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while processing persistence.xml from URL: file:/C:/paul/oneView/java/de.vogella.jpa.simple/build/eclipse/
Internal Exception:
(1. The markup in the document preceding the root element must be well-formed.)
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionLoadingFromUrl(PersistenceUnitLoadingException.java:100)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processPersistenceArchive(PersistenceUnitProcessor.java:597)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.getPersistenceUnits(PersistenceUnitProcessor.java:481)
at org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.findPersistenceUnitInfoInArchive(JPAInitializer.java:172)
at org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.findPersistenceUnitInfoInArchives(JPAInitializer.java:154)
at org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.findPersistenceUnitInfo(JPAInitializer.java:135)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:177)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at de.vogella.jpa.simple.main.Main.main(Main.java:17)
I receive the following error in my standalone java application:
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named DataSourcePostgres
Here's my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="DataSourcePostgres">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>Denarnica</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.ProgressDialect"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<!--<property name="hibernate.show_sql" value="true"/>-->
<property name="hibernate.connection.username" value="*****"/>
<property name="hibernate.connection.password" value="*******"/>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/postgres"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
and here's my Server.java:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;
public class Server {
private static final String PERSISTENCE_UNIT_NAME = "DataSourcePostgres";
private static EntityManagerFactory factory;
public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// Read the existing entries and write to console
Query q = em.createQuery("select d from Data d");
List<Denarnica> dataList= q.getResultList();
System.out.println("Size: " + dataList.size());
}
}
I've been looking at some similar problems, but the solutions people suggested to them don't seem to help me. Any advice?
My problem was I didn't put the persistence.xml into a META-INF folder. After I fixed that everything worked.
We are facing an issue while calling the stored procedure from the application.
The database is oracle 10g
This proc has 2 input parameters and 2 output parameters.
Input 1:- DB-List
Input 2:- String
Output 1:-Again a DB-List
Output 2:- Number
When we are trying to use
Query q = session.createSQLQuery("{call proc_name(?,?,?,?)}");
We cannot distinguish between in parameters and out parameters.
So how should we handle it by using this.
Also,
We tried to use callable statement as follows:
Session session = (Session) getEntityManager().getDelegate();
SessionImpl sessionImpl = ((SessionImpl) getEntityManager().getDelegate());
Connection cc = sessionImpl.connection();
CallableStatement callableStatement = null;
callableStatement = cc.prepareCall("{call proc_name(?,?,?,?)}");
ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor("DB_LIST",callableStatement.getConnection());
ARRAY paramArray = new ARRAY(descriptor, callableStatement.getConnection(), array);
callableStatement.setArray(1, paramArray);
callableStatement.setString(2, "N");
callableStatement.registerOutParameter(3, OracleTypes.ARRAY, "DB_RETURN_LIST");
callableStatement.registerOutParameter(4, Types.INTEGER);
// executing the query
callableStatement.execute();
We get the following error:
javax.ejb.EJBException: java.lang.ClassCastException:
$Proxy50 cannot be cast to oracle.jdbc.OracleConnection
Can you please provide some suggestions.
This is the Entity Manager that we are using
public abstract class GenericDAO<T, ID extends Serializable> implements IGenericDAO<T, ID> {
private final Class<T> persistentClass;
#PersistenceContext(unitName = "firstPersistenceUnit")
#Produces
private EntityManager entityManager;
public void setEntityManager(final EntityManager entityManager) throws DataAccessException {
this.entityManager = entityManager;
}
public EntityManager getEntityManager() throws DataAccessException {
return entityManager;
}
}
Here is the entry in the Persistance.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="firstPersistenceUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/firstDataSource</jta-data-source>
<class>com.domain.Branch</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<validation-mode>AUTO</validation-mode>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
<persistence-unit name="secondPersistenceUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/secondDataSource</jta-data-source>
<class>com.domain.PocJeeCounty</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<validation-mode>AUTO</validation-mode>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
Dont use second way, instead create and define query and query parameters using #NamedStoredProcedureQuery and #StoredProcedureParameter. Following is the code for your requirement
#NamedStoredProcedureQuery(
name="PROC_NAME",
procedureName="proc_name",
returnsResultSet=true/false,
parameters={
#StoredProcedureParameter(queryParameter="param1",name="p1",direction=Direction.IN,type=Integer.class),
#StoredProcedureParameter(queryParameter="param2",name="p2",direction=Direction.IN,type=Timestamp.class),
#StoredProcedureParameter(queryParameter="param3",name="p3",direction=Direction.OUT,type=String.class),
#StoredProcedureParameter(queryParameter="param4",name="p4",direction=Direction.OUT,type=Integer.class)
}
)
and use em.createNativeQuery() method