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);
Related
I'm trying to implement a JAX-WS web service which has an endpoint that returns data from the configured data source. I managed to create the service and the client, but I can't access the database because I get Null Pointer Exceptions when I try to use the injected EntityManager.
Here is my service:
#WebService(serviceName="ViewDocuments")
public class ViewDocumentService {
#PersistenceContext(unitName = "HibernateJPA")
private EntityManager em;
#WebMethod
public String sayHello() {
return "Hello world!";
}
#Produces("application/json")
#WebMethod(operationName="getDocuments")
public List<File> getDocuments(#WebParam(name = "name") String filename) {
if(filename == null)
return em.createQuery("FROM File").getResultList();
else return null;
}
}
And here is my WebServiceClient:
#WebServiceClient(name="ViewDocuments", wsdlLocation = "http://localhost:8080/lab8/ViewDocuments?wsdl")
public class ViewDocumentClient extends Service {
protected ViewDocumentClient(URL wsdlDocumentLocation, QName serviceName) {
super(wsdlDocumentLocation, serviceName);
}
#WebEndpoint(name = "DocumentPort")
public ViewDocumentService getDocumentPort() {
return new ViewDocumentService();
}
}
I am trying to call the function here:
public class MainDocumentClient {
public static void main(String[] args) throws Exception {
URL wsdlUrl = new URL("http://localhost:8080/lab8/ViewDocuments?wsdl");
QName serviceName = new QName("http://webservices/", "ViewDocuments");
ViewDocumentClient service = new ViewDocumentClient(wsdlUrl, serviceName);
ViewDocumentService viewDocumentService = service.getDocumentPort();
System.out.println(viewDocumentService.sayHello());
System.out.println(viewDocumentService.getDocuments(null));
}
}
This is my persistence.xml file content:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
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_2.xsd">
<persistence-unit name="HibernateJPA" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>java:/Postgres-Source8</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL95Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.archive.autodetection" value="class, hbm" />
</properties>
</persistence-unit>
<persistence-unit name="HibernateJPAForTests" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/lab8" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.user" value="postgres" />
<property name="javax.persistence.jdbc.password" value="<password>" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL95Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.archive.autodetection" value="class, hbm" />
</properties>
</persistence-unit>
</persistence>
The sayHello() method works fine. I also tried to use an EntityManagerFactory, to instantiate my Repository by hand, to add the #Stateless annotation, but nothing seems to work. I just can't query my database.
After lots of research, I still can't seem to understand how to properly inject the EntityManager. Can someone explain this to me, please?
I am using Wildfly21.0.0.
I want to use entity manager from container, but when I try to access it I get
java.lang.IllegalStateException: Need active coordination
persistence.xml
<persistence-unit name="data-point" transaction-type="JTA">
<jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=dvdrental)</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.archive.autodetection" value="class"/>
</properties>
bluprint.xml
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd"
default-activation="eager"
xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.2.0"
xmlns:jpa="http://aries.apache.org/xmlns/jpa/v2.0.0">
<jpa:enable />
<tx:enable-annotations />
<service id="filesEntityManager" ref="filesEntityManagerImpl" interface="ru.bia.karaf.dao.FilesEntityManager"/>
<bean id="filesEntityManagerImpl" class="ru.bia.karaf.dao.FilesEntityManagerImpl"/>
<bean id="testBean" class="ru.bia.karaf.web.TestBean" init-method="test">
<property name="filesEntityManager" ref="filesEntityManagerImpl"/>
</bean>
TestBean.java
public class TestBean {
private FilesEntityManagerImpl filesEntityManager;
public void test(){
System.out.println("hey bro from init");
System.out.println("filesEntityManager = " + filesEntityManager);
System.out.println("filesEntityManager.getEm() = " + filesEntityManager.getEm());
}
public FilesEntityManagerImpl getFilesEntityManager() {
return filesEntityManager;
}
public void setFilesEntityManager(FilesEntityManagerImpl filesEntityManager) {
this.filesEntityManager = filesEntityManager;
}
}
FilesEntityManagerImpl.java
#OsgiServiceProvider(classes = {FilesEntityManager.class})
#Transactional
public class FilesEntityManagerImpl implements FilesEntityManager {
#PersistenceContext(unitName="data-point")
EntityManager em;
...
}
The EntityManager that is injected into FilesEntityManagerImpl is a thread local proxy of the EntityManager. Its lifecycle is bound to a Coordination.
If you access em outside of a Coordination you get this error. You can make sure a Coordination is active by using the #Transactional annotations. If you
do not need an actual transaction but only the Coordination then use #Transactional(TxType.SUPPORTS).
You should also generally not access the EntityManager outside of the object that is injected with it.
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;
}
}
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.
I'm pretty new to JPA and HSQLDB, and I'm havin a weird error when I'm trying to create my EntityManagerFactory. Its a Web Dynamic project in Eclipse (with Tomcat 6.0 as web server) and I imported all the libraries in the the WEB-INF/lib. I'm trying to create the Entity manager Factory in a servlet but in just gives me a class not found exception on the line
emf = Persistence.createEntityManagerFactory("manager1");
Here is the code I used in my servlet:
package view;
import java.io.IOException;
import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.ThemeLivre;
public class AjouterTheme extends HttpServlet {
//private static final long serialVersionUID = 1L;
#PersistenceUnit(unitName ="DB")
private EntityManagerFactory emf;
public AjouterTheme() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
emf = Persistence.createEntityManagerFactory("DB");
EntityManager em = emf.createEntityManager();
String nomTheme = request.getParameter("nomtheme");
String descTheme = request.getParameter("desctheme");
EntityTransaction tx = em.getTransaction();
tx.begin();
ThemeLivre thml = new ThemeLivre(nomTheme, descTheme);
em.persist(thml);
tx.commit();
}
}
Here is my persistence.xml
<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="DB" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/DefaultDS</jta-data-source>
<class>model.ThemeLivre</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.url" value="jdbc:hsqldb:hsql://localhost/"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
Please tell me what I did wrong, or if there is something I can do.
Thank you
In your servlet code you used
#PersistenceUnit(unitName ="DB")
private EntityManagerFactory emf;
but you declare
<persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
change either the one or the other persistence unit name.
Following your input above
Try to add the hibernate persistence provider lib. You add only the specification (API). The implementation itself (hibernate) is needed, to create an Entity Manager.