1
I created an Entitymanager producer in a project .jar
but the same 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 an empty Beans.xml file in src/main/Resources/META-INF
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 did the test below but returns:
java.lang.Nullpointerexception in the entityManager.getTransaction() line. 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() );
}
}
When you run junit the CDI is not initialized, so the objects are not instantiated. Use jGlue to test, below: http://jglue.org/cdi-unit/. Add dependency and follow this tutorial for use: http://jglue.org/cdi-unit-user-guide/.
– adelmo00
Well that, thank you.
– Marcelo
Blz. I put an answer to leave registered and help others who have the same problem. Hugs
– adelmo00
See if you can help me.
– Marcelo
You are placing this jar inside a container(wildfly, jboss, glassfish)?
– adelmo00
Not right now. The idea is to create a jar that I will use in several War projects. In other words, I am creating a jar project that Maven will include in a War
– Marcelo
Let’s go continue this discussion in chat.
– adelmo00