How can I get an entity manager in a normal java class? I tried it with Injection, but without any result, I always get a NullPointerException:
public class ClassName {
@PersistenceContext(unitName = "myPU")
public EntityManager em;
@Resource
UserTransaction utx;
...
Then I tried it with a seperate class that provides the EntityManagerFactory, also without success, NullPointerException is thrown:
public class HibernateUtil {
private static EntityManagerFactory entityManagerFactory = null;
static {
try {
entityManagerFactory = Persistence.createEntityManagerFactory("myPU");
} catch (Throwable e) {
e.printStackTrace();
}
}
public static EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
}
Help is appreciated.
You have no Dependency.Injection here, if not running within a Java EE-Container.
These attributes are null. You need to initialize them first (Or add spring or another DI-container).