Mike Argyriou
Mike Argyriou

Reputation: 1310

getting EntityManager from an unmanaged class

How can I get the EntityManager from a class that is not an EJB? Moreover this class isn't managed by the container. Can I get a reference from the JNDI? Is there ANY way?

Thanks

Upvotes: 3

Views: 7586

Answers (3)

Theofanis
Theofanis

Reputation: 637

EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnitName");
EntityManager entityManager =  factory.createEntityManager();

I tested it and it works.

source

Upvotes: 0

Brett Kail
Brett Kail

Reputation: 33936

First, you'll need to declare a persistence unit/context reference. If you want to use @PersistenceUnit(name="jpa/pu", unitName="...") or @PersistenceContext(name="jpa/pc", unitName="...") annotations, these must be placed on an injection-capable class (e.g., on a servlet or EJB class), and if you just want to use them from outside the injection-capable class, you can put them on the class (possibly within @PersistenceUnits or @PersistenceContexts container annotations if you have several). Alternatively, you can specify the same metadata in web.xml (or ejb-jar.xml).

Second, you'll need to perform a JNDI lookup using the name declared in the reference. Using the examples above, this would be something like:

EntityManagerFactory emf = (EntityManagerFactory) new InitialContext().lookup("java:comp/env/jpa/pu");
EntityManager em = (EntityManager) new InitialContext().lookup("java:comp/env/jpa/pc");

Note that the lookup must be performed within the context of the declared references. For example, if your servlet calls another class that uses JPA, then you'll need to declare the references in web.xml (or annotate a servlet class). If your servlet calls an EJB that calls another class that uses JPA, then you'll need to declare the references in ejb-jar.xml for that EJB (or annotate the EJB).

Upvotes: 4

ChristopherS
ChristopherS

Reputation: 883

EntityManager em = (EntityManager) new InitialContext().lookup("java:comp/env/persistence/em");

Upvotes: 0

Related Questions