Via annotation
Both lookup and injection of an EntityManager can be configured via the @PersistenceContext annotation.
Code Block | ||
---|---|---|
| ||
package org.superbiz; import javax.persistence.PersistenceContext; import javax.persistence.EntityManager; import javax.ejb.Stateless; import javax.naming.InitialContext; @Stateless @PersistenceContext(name = "myFooEntityManager", unitName = "foo-unit") public class MyBean implements MyInterface { @PersistenceContext(unitName = "bar-unit") private EntityManager myBarEntityManager; public void someBusinessMethod() throws Exception { if (myBarEntityManager == null) throw new NullPointerException("myBarEntityManager not injected"); // Both can be looked up from JNDI as well InitialContext context = new InitialContext(); EntityManager fooEntityManager = (EntityManager) context.lookup("java:comp/env/myFooEntityManager"); EntityManager barEntityManager = (EntityManager) context.lookup("java:comp/env/org.superbiz.MyBean/myBarEntityManager"); } } |
Via xml
The above @PersistenceContext annotation usage is 100% equivalent to the following xml.
...