I created an EntityManager producer on a .jar
project but it does not work.
I configured POM.XML with the dependency below
<!-- CDI -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
</dependency>
-
I created a producer file according to abaix
import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; public class JpaUtil { private static final String PERSISTENCE_UNIT = "PEROLAWEB"; private static ThreadLocal<EntityManager> threadEntityManager = new ThreadLocal<EntityManager>(); private static EntityManagerFactory entityManagerFactory; @Produces public EntityManager geraEM(){ System.out.println("\n---------- injectou EntityManeger Criou "); if( entityManagerFactory == null || !entityManagerFactory.isOpen()) { entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); } EntityManager entityManager = threadEntityManager.get(); if(entityManager == null || !entityManager.isOpen() ) { entityManager = entityManagerFactory.createEntityManager(); JpaUtil.threadEntityManager.set(entityManager); } return entityManager; } public void finaliza(@Disposes EntityManager entityManager) { System.out.println("\n---------- destruiu EntityManeger Criou "); if(entityManager!=null){ EntityTransaction entityTransaction = entityManager.getTransaction(); if(entityTransaction.isActive()){ if(entityTransaction.getRollbackOnly()) { entityTransaction.rollback(); }else{ entityTransaction.commit(); } } entityManager.close(); threadEntityManager.set(null); } } }
- I took the test below but it returns:
I created an empty beans.xml file in src / main / resources / META-INF
java.lang.NullPointerException in the entityManager.getTransaction (). begin (); **
import javax.inject.Inject;
import javax.persistence.EntityManager;
import org.junit.Assert;
import org.junit.Test;
public class TesteEntityManagerFactory {
@Inject
private EntityManager entityManager;
@Test
public void testeDeConexao(){
entityManager.getTransaction().begin();
Assert.assertTrue(entityManager.getTransaction().isActive() );
}
}