h1. Via annotation
Both lookup and injection of an EntityManager can be configured via the @PersistenceContext annotation.
{code:title=Usable by EJB, Interceptor, Servlet, Filter, or Listener}
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");
}
}
{code}
h1. Via xml
The above @PersistenceContext annotation usage is 100% equivalent to the following xml.
{code:xml|title=ejb-jar.xml or web.xml}
myFooEntityManager
foo-unit
Transaction
org.superbiz.calculator.MyBean/myBarEntityManager
bar-unit
Transaction
org.superbiz.calculator.MyBean
myBarEntityManager
{code}