2016-09-30 38 views
1

我想創建一個EntityManager產生使用在事務性攔截器,因爲我在tomcat中使用CDI。EntityManager null @Produces

所以,這是我的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; 

    } 

} 

但是當我嘗試此代碼的EntityManager中始終EntityManagerProducer類返回NULL。哪裏不對 ?

回答

1

該位

@PersistenceContext 
private EntityManager entityManager; 

只能保證在Java EE環境中工作,而不是簡單的Servlet容器如Tomcat。

+0

謝謝,我自己創建EntityManager。 – RonaldoLanhellas