简体   繁体   中英

How do I get @PersistenceContext to load my EntityManager in CDI?

I'm currently looking at building a new application without using Spring, rather I'm trying to do all of my injection using CDI.

I have a DAO that looks like the following:


@TransactionManagement(TransactionManagementType.CONTAINER)
public class TestDao
{
    @PersistenceUnit(unitName="DefaultPersistenceUnit")
    private EntityManagerFactory emf;

    @PersistenceContext(unitName="DefaultPersistenceUnit")
    private EntityManager em;

    @TransactionAttribute(TransactionAttributeType.MANDATORY)
    public void test ( )
    {
        System.err.println ("EMF == " + emf);
        System.err.println ("EM == " + em);
    }
}

When I run the test method, I see the following:

EMF == org.apache.openejb.assembler.classic.ReloadableEntityManagerFactory@1e3b8c4
EM == null

So its fairly obvious that my EntityManager is not getting loaded by CDI. It seems like it should, but no joy.

I've tried hosting on both TomEE and WebSphere Liberty profile, but the effect is the same in both cases.

Can someone point me in the right direction? I'm stumped...

Thanks...

The @PersistenceContext and @TransactionManagement are used by EJB. To make it work your component must be EJB. Add @Stateless to your class to make it work. You will need ejb project or nest bean in war.

To be honest, I'm not sure why are you trying to inject both of them, it should throw errors, because, from my experience, persistence is injected either by @PersistenceContext for EntityManager or @PersistenceUnit for EntityManagerFactory , not both. Also, you can get EntityManager from EntityManagerFactory with createEntityManager() method, so I don't understand the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM