【发布时间】:2016-09-30 18:19:47
【问题描述】:
我正在尝试创建一个 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 中 @Inject 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。怎么了?
【问题讨论】: