我正在尝试创建要在事务拦截器中使用的EntityManager产品,因为我在tomcat中使用了CDI。

因此,这是我的EntityManagerProducer类:

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();
        }
    }

}


之后,我@在TransactionalInterceptor中注入EntityManager,请参阅:

@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;

    }

}


但是,当我尝试此代码时,EntityManagerProducer类中的EntityManager始终返回NULL。怎么了 ?

最佳答案

这一点

@PersistenceContext
private EntityManager entityManager;


只能保证在Java EE环境中工作,而不能在像Tomcat这样的Servlet容器中工作。

09-26 12:52