EJB3 persistence in a Tomcat webapp (ThreadLocal pattern)

When you only want to use EJB3 persistence, and not the whole EJB3 stack).

First posted to http://forum.hibernate.org/viewtopic.php?t=963478 without an answer!

In the document "Using Hibernate with Tomcat" (http://www.hibernate.org/114.html), it is suggested that you create a ServletContextListener - like the one below - where the listener initializes and closes Hibernate on deployment and undeployment of your webapp.

publicclass HibernateListenerimplements ServletContextListener{

publicvoid contextInitialized(ServletContextEvent event){

HibernateUtil.getSessionFactory();// Just call the static initializer of that class

}

publicvoid contextDestroyed(ServletContextEvent event){

HibernateUtil.getSessionFactory().close();// Free all resources

}

}

My question is: If I want to use Hibernate as an EJB3 persistence engine in a Webapp running in Tomcat, do I make a similar ServletContextListener like this:

publicclass EntityManagerListenerimplements ServletContextListener{

publicvoid contextInitialized(ServletContextEvent event){

EntityManagerUtil.getEntityManagerFactory();// Just call the static initializer of that class

}

publicvoid contextDestroyed(ServletContextEvent event){

EntityManagerUtil.getEntityManagerFactory().close();// Free all resources

}

}

publicclass EntityManagerUtil{

privatestatic EntityManagerFactory emf;

publicstaticfinal ThreadLocal<EntityManager> entitymanager =new ThreadLocal<EntityManager>();

publicstatic EntityManagerFactory getEntityManagerFactory(){

if (emf ==null){

// Create the EntityManagerFactory

emf = Persistence.createEntityManagerFactory("example");

}

return emf;

}

publicstatic EntityManager getEntityManager(){

EntityManager em = entitymanager.get();

// Create a new EntityManager

if (em ==null){

em = emf.createEntityManager();

entitymanager.set(em);

}

return em;

}

publicstaticvoid closeEntityManager(){

EntityManager em = entitymanager.get();

entitymanager.set(null);

if (em !=null) em.close();

}

}

And then in my webapp use the following code:

public Person findByName(String name){

EntityManager em = EntityManagerUtil.getEntityManager();

Query q = em.createQuery("select person from Person as person where name=:param");

q.setParameter("param", name);

Person p = (Person) q.getSingleResult();

em.close();

return p;

}

Would that be the right way to do it?

[4952 byte] By [NPStrandberga] at [2007-10-3 2:55:29]
# 1
Sun's reference JPA implementation (= EJB3 persistence) can be obtained fromhttps://glassfish.dev.java.net/downloads/persistence/JavaPersistence.html
m_fuchsa at 2007-7-14 20:44:35 > top of Java-index,Enterprise & Remote Computing,Enterprise Technologies...