简体   繁体   中英

@PersistenceContext is always null

I'm trying to get CDI (with Open Web Beans) working from within a unit test using Delta Spike ( @RunWith(CdiTestRunner.class) ). Dependency injection is working fine but my EntityManagerFactory is always null:

public class EntityManagerProducer {

    @PersistenceContext(unitName = "sbPersistenceUnit")
    private EntityManagerFactory emf;  //Always null

    @Produces
    public EntityManager create() {            
        return emf.createEntityManager();
    }

    public void close(@Disposes EntityManager em) {
        if (em.isOpen()) {
            em.close();
        }
    }
}

I know that my persistence.xml is okay because I can create the Session Factory manually:

EntityManagerFactory test = Persistence.createEntityManagerFactory("sbPersistenceUnit");

and all other injections are working fine. Does anybody know what might be missing?

You will need to use @PersistenceUnit to inject EntityManagerFactory. @PersistentContext is used for EntityManager injection.

In an unit-test you aren't in a managed environment. OpenWebBeans would support it via the openwebbeans-resource module + @PersistenceUnit, but that isn't portable. So you need to use eg:

@Specializes
public class TestEntityManagerProducer extends EntityManagerProducer {
    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("...");

    @Produces
    //...
    @Override
    protected EntityManager create() {
        return emf.createEntityManager();
    }

    @Override
    protected void close(@Disposes EntityManager em) {
        if (em.isOpen()) {
            em.close();
        }
    }
}

in the test-classpath

If you ask such questions on their mailing-list, you get answers petty quickly.

Do you define your entitymanagerFactory as a bean?

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> 
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

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