JPA in practice
JPA (Java Persistence API) makes promises about injection of references and
behavior through magic annotations like @Entity and @PersistenceContext. To
keep those promises, JPA apps must deploy into containers that know how to
inject, like GlassFish or Spring or (supposedly) Java Server Faces (JSF). You
can still use JPA without injection in a leaner Tomcat environment.
The key enablers to JPA are EntityManagerFactory and EntityManager. You
define a bunch of @Entity classes to pull database information into your
object model as value objects. Logic instances, i.e., business processes that
use these entities need an EntityManager to bind the objects to their data
store backing. For non-injected environments like plain Tomcat, you use a
static method to create the factory:
public class Util
{
private static final String PUNIT = "projectPU";
private static final EntityManagerFactory EMFCANON =
Persistence.createEntityManagerFactory( PUNIT );
public static EntityManagerFactory getEmf()
{
return EMFCANON;
}
}
The factory will be heavy but thread safe. Request processors get their
lightweight, non-thread-safe EntityManagers from the common factory:
public class BizProcess
{ ...
public String submit()
{
EntityManager emgr = Util.getEmf().createEntityManager();
try
{
Entity e = new Entity();
fill( e );
emgr.getTransaction().begin();
emgr.merge( e );
emgr.getTransaction().commit();
}
finally
{
emgr.close();
}
}
}
Not as sexy as @PersistenceContext() but it works.
--
Lew