EntityManager
From CauchoWiki
[edit] API
public interface EntityManager {
public <T> T find(Class<T> entityClass, Object key);
public <T> T getReference(Class<T> entityClass, Object key);
public void refrech(Object entity);
public void persist(Object entity);
public <T> T merge(T entity);
public void remove(Object entity);
public Query createQuery(String sql);
public Query createNamedQuery(String name);
public Query createNativeQuery(String sql, Class resultClass);
public Query createNativeQuery(String sql, String resultSetMapping);
public boolean contains(Object entity);
public void clear();
public void flush();
public boolean isOpen();
public void close();
public void setFlushMode(FlushModeType flushMode);
public FlushModeType getFlushMode();
public void lock(Object entity, LockModeType lockMode);
public EntityTransaction getTransaction();
}
[edit] @PersistenceContext injection
The EntityManager for a persistence unit can be assigned using EJB injection with the @PersistenceContext annotation.
The @PersistenceContext EntityManager is a proxy ThreadLocal. In other words, the underlying EntityManager is specific to the request thread and is thread-safe. Different request threads for the same @PersistenceContext proxy will be using different underlying EntityManagers.
The configuration for a servlet might look like:
public class MyServlet extends GenericServlet {
@PersistenceContext
EntityManager _em;
public void service(ServletRequest req, ServletResponse res)
{
TestBean test = _em.find(TestBean.class, new Integer(1));
...
}
}
@PersistenceContext(unitName="xxx") can be used if the environment has more than one persistence unit.
@PersistenceContext can be used for session beans, message-driver beans, servlets, filters, and JSP pages.
[edit] Obtaining an EntityManager using JNDI
In Amber, the EntityManager for a persistence unit is stored as "java:comp/env/persistence/PersistenceContext/xxx", where "xxx" is the name of the persistence unit.
(The CMP 2.1 implementation uses a name of "resin-ejb".)
