我试图创建一个EntityManager产生在Transactional Interceptor中使用,因为我在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();
}
}
}
在此之后我@Inject在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。有什么问题?
答案 0 :(得分:1)
这一位
@PersistenceContext
private EntityManager entityManager;
只能保证在Java EE环境中工作,但不能像Tomcat那样仅仅在Servlet容器中工作。