我試圖注入一個EntityManager到我的應用程序使用CDI但EntityManager嘗試使用它爲空。注入EntityManager始終爲空
這是我的代碼,我跟着幾個關於如何注入EntityManager的教程,我使用了與那些教程中相同的代碼。
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface DevDatabase {
}
@Singleton
public class JPAResourceProducer {
@Produces
@PersistenceContext(unitName = "DevPU")
@DevDatabase
private EntityManager em;
}
persistence.xml中
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="DevPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>entity.MyEntity</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/MyDB"/>
<property name="javax.persistence.jdbc.user" value="appuser"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.password" value="apppassword"/>
</properties>
</persistence-unit>
</persistence>
這是我如何使用它在我的DAO
public abstract class GenericDAO<T> {
@DevDatabase
@Inject
private EntityManager em;
private final Class<T> entityClass;
public GenericDAO(Class<T> entityClass) {
this.entityClass = entityClass;
}
public void beginTransaction() {
em.getTransaction().begin();
}
}
混凝土DAO
public class MyEntityDAO extends GenericDAO<MyEntity> {
public MyEntityDAO() {
super(MyEntity.class);
}
}
在我的代碼
而且某處時,我請撥打電話myEntityDao.beginTransaction()
我得到一個NullPointerException
導致注入的EntityManager
爲空。
有什麼我在我的製片人失蹤?
你使用spring還是J2EE? – WeMakeSoftware
我不使用彈簧,我使用Tomcat作爲容器,我提供了焊接servlet.jar – jerome
發佈焊接配置 – WeMakeSoftware