I am getting a NullPointerException when trying to access the EntityManager
via annotation PersistenceContext
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
@Stateless
public class UserService {
@PersistenceContext(unitName = "jcrdb")
private EntityManager em;
...
}
My persistence.xml
in path src/main/webapp/META-INF
:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="jcrdb" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<!-- <jta-data-source>jdbc/jcrdb</jta-data-source> -->
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<!-- this tell Hibernate to update the DDL when it starts, very useful
for development, dangerous in production -->
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="javax.persistence.logging.level" value="INFO" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://127.0.0.1:5432/jcrdb" />
<property name="javax.persistence.jdbc.user" value="jcr_admin" />
<property name="javax.persistence.jdbc.password" value="q1w2e3r4" />
<!-- <property name="tomee.jpa.factory.lazy" value="true" />-->
</properties>
</persistence-unit>
</persistence>
The User
-class:
@Entity
@Table(name = "Users")
public class User {
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
private int UserId;
private String alias;
private String email;
@OneToOne(fetch = FetchType.LAZY)
private Person person;
@OneToMany
private List<Role> roles;
public User() {
}
// constructor, getters, setters...
}
There is no problem getting the EntityManager directly like this:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jcrdb");
em = entityManagerFactory.createEntityManager();
I tried running this in jetty and tomEE.
It seems to me that the ejb-stuff isn't working. What am I missing here (new to all this)?