(When you only want to use EJB3 persistence, and not the whole EJB3 stack).
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.
Code:
public class HibernateListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
HibernateUtil.getSessionFactory(); // Just call the static initializer of that class
}
public void 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:
Code:
public class EntityManagerListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
EntityManagerUtil.getEntityManagerFactory(); // Just call the static initializer of that class
}
public void contextDestroyed(ServletContextEvent event) {
EntityManagerUtil.getEntityManagerFactory().close(); // Free all resources
}
}
Code:
public class EntityManagerUtil {
private static EntityManagerFactory emf;
public static final ThreadLocal<EntityManager> entitymanager = new ThreadLocal<EntityManager>();
public static EntityManagerFactory getEntityManagerFactory() {
if (emf == null) {
// Create the EntityManagerFactory
emf = Persistence.createEntityManagerFactory("example");
}
return emf;
}
public static EntityManager getEntityManager() {
EntityManager em = entitymanager.get();
// Create a new EntityManager
if (em == null) {
em = emf.createEntityManager();
entitymanager.set(em);
}
return em;
}
public static void closeEntityManager() {
EntityManager em = entitymanager.get();
entitymanager.set(null);
if (em != null) em.close();
}
}
And then in my webapp use the following code:
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?