jerome
jerome

Reputation: 2089

Injecting EntityManager always null

I'm trying to inject an EntityManager into my application using CDI but the EntityManager is null when trying to use it.

Here is my code I followed several tutorial on how to inject EntityManager and I use the same code as in those tutorial.

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface DevDatabase {

}


@Singleton
public class JPAResourceProducer {

    @Produces
    @PersistenceContext(unitName = "DevPU")
    @DevDatabase
    private EntityManager em;
}

the 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>

This is how I use it in my 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();
    }
}

Concrete DAO

public class MyEntityDAO extends GenericDAO<MyEntity> {

    public MyEntityDAO() {
        super(MyEntity.class);
    }
}

And somewhere in my code when I call for exemple myEntityDao.beginTransaction() I get a NullPointerException cause the injected EntityManager is null.

Is there anything I am missing in my producer ?

Upvotes: 1

Views: 5085

Answers (1)

Benjamin
Benjamin

Reputation: 1846

@PersistenceContext does not work out-of-the-box in a servlet container like tomcat. It works in a Java EE container.

So your EntityManager field stays to null because @PersistencContext has no effect in Tomcat, even using Weld-servlet.

You may add a ServletListener to bootstrap a JPA implementation, probalby hibernate in your case. Then you may obtain EntityManagerinstances through @Inject.

Note that you should also provide a JPA implementation (like hibernate), the same way you did for Weld.

You can try doing something like: Injecting EntityManager with a producer in tomcat

Upvotes: 5

Related Questions