Search code examples
javajpacdi

EntityManager null in @Produces


I'm trying to create a EntityManager produces to use in a Transactional Interceptor, because i'm using CDI within tomcat.

So, this is my EntityManagerProducer class:

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@RequestScoped
public class EntityManagerProducer {

    @PersistenceContext
    private EntityManager entityManager;

    @Produces
    @RequestScoped
    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void closeEntityManager(@Disposes EntityManager em) {
        if (em != null && em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (em != null && em.isOpen()) {
            em.close();
        }
    }

}

After this i @Inject the EntityManager in TransactionalInterceptor, see:

@Transactional
@Interceptor
public class TransactionalInterceptor {

    private static Logger log = Logger.getLogger(TransactionalInterceptor.class);

    @Inject
    private EntityManager em;

    @AroundInvoke
    public Object manageTransaction(InvocationContext context) throws NotSupportedException, SystemException{
    em.getTransaction().begin();
    log.debug("Starting transaction");
    Object result = null;
    try {
        result = context.proceed();
        em.getTransaction().commit();
        log.debug("Committing transaction");
    } catch (Exception e) {
        log.error(e);
        em.getTransaction().rollback();
    }
    return result;

    }

}

But when i try this code the EntityManager in EntityManagerProducer class always return NULL. What is wrong ?


Solution

  • This bit

    @PersistenceContext
    private EntityManager entityManager;
    

    is only guaranteed to work in a Java EE environment, but not in a mere Servlet Container like Tomcat.