EntityManagerFactory
From CauchoWiki
The EntityManagerFactory produces EntityManger instances for applications.
In many applications, it is more convenient to get the persistence context EntityManager directly using @PersistenceContext or JNDI, rather than using an EntityManagerFactory.
[edit] API
package javax.persistence;
public interface EntityManagerFactory {
public EntityManager createEntityManager();
public EntityManager createEntityManager(PersistenceContextType type);
public EntityManager getEntityManager();
public boolean isOpen();
public void close();
}
- createEntityManager() creates a new EntityManager with a TRANSACTIONAL PersistenceContextType.
- createEntityManager(type) creates a new EntityManager with an application-specified PersistenceContextType.
- getEntityManager() returns the ThreadLocal EntityManager for the persistence unit, i.e. the persistence context. Using @PersistenceUnit in combination with getEntityManager() is equivalent to use @PersistenceContext.
- isOpen() checks if the EntityManagerFactory is valid.
- close() closes the EntityManagerFactory.
[edit] @PersistenceUnit injection
The EntityManagerFactory for a persistence unit can be assigned using EJB injection with the @PersistenceUnit annotation. The configuration for a servlet might look like:
public class MyServlet extends GenericServlet {
@PersistenceUnit
EntityManagerFactory _emf;
public void service(ServletRequest req, ServletResponse res)
{
EntityManager em = _emf.createEntityManager();
...
}
}
@PersistenceUnit(unitName="xxx") can be used if the environment has more than one persistence unit.
@PersistenceUnit can be used for session beans, message-driver beans, servlets, filters, and JSP pages.
In many cases, the @PersistenceContext is more appropriate, since it injects a JTA-aware EntityManager directly.
[edit] Obtaining an EntityManagerFactory using JNDI
In Amber, the EntityManagerFactory for a persistence unit is stored as "java:comp/env/persistence/PersistenceUnit/xxx", where "xxx" is the name of the persistence unit.
(The CMP 2.1 implementation uses a name of "resin-ejb".)
