Inject PersistenceContext with CDI

后端 未结 2 1418
孤城傲影
孤城傲影 2020-12-19 22:31

Currently, I\'m using PersistenceContext to inject an EntityManager. The EM is injected perfectly.

@Stateless
public StatelessSessionBean implements Stateles         


        
相关标签:
2条回答
  • 2020-12-19 22:46

    @PersistenceContext is an EJB injection point, while @Inject is a CDI one

    Actually, no. @PersistenceContext annotation can be used in CDI and is not connected with EJB. You can do something like this:

    @Named
    public class EntityDAO {
        @PersistenceContext
        private EntityManager manager;
    
        ...
    
    }
    

    EJB uses @EJB annotation to inject other EJB, but it can inject any CDI bean or persistence context with same annotations.

    0 讨论(0)
  • 2020-12-19 23:06

    The best practice for persistence context and CDI is to make them CDI bean to avoid these kind of issue.

    public class MyProducers {
        @Produces
        @PersistenceContext(unitName = "MyPersistenceUnit")
        private EntityManager em;
    }
    

    After that you'll be able to inject the EntityManager in CDI way. Taking your EJB it'll be :

    @Stateless
    public StatelessSessionBean implements StatelessSessionBeanLocal {
    
        @Inject
        private EntityManager em;
    
        @Override
        public Collection<MyObject> getAllObjects(){
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriqQuery<MyObject> query = cb.createQuery(MyObject.class);
            query.from(MyObject);
            return em.createQuery(query).getResultList();
        }
    }
    

    This way, you'll be able to decorate your CDI bean with no issue.

    If you have multiple EntityManagers you can use CDI qualifiers to distinguish them

    0 讨论(0)
提交回复
热议问题