Sunday, April 24, 2011

Hibernate - Part 5 - Storing Hibernate SessionFactory with Struts

I'm working on a relatively simple web project using Struts 2 and Hibernate.  I'm not planning on using any EJB's so my persistence code will be directly accessible by my Struts Action classes.  For performance reasons, I know it is recommended to minimize the times you create the Hibernate Configuration and SessionFactory objects.

I did some Googling and didn't find much in the way of best practices for using Struts and Hibernate.  I figured it would make sense to create the Hibernate SessionFactory once and add it to the ServletContext so that it is available for the life of the application.  I found an example of this technique here and adapted it for my application.

I noticed the example created the SessionFactory and added it to the ServletContext but never closed it.  I added code to the contextDestroyed method of my ServletContextListener class to destroy the SessionFactory at shutdown.  I've run this by a couple of people and received differing opinions on whether it is necessary to close it but I don't think there is any harm in doing so.

Here's a snippet of the code I'm using:

public class HibernateListener implements ServletContextListener {

private Configuration config;
private SessionFactory sessionFactory;
private String path = "/hibernate.cfg.xml";

public static final String KEY_NAME = HibernateListener.class.getName();

@Override
public void contextDestroyed(ServletContextEvent arg0) {
    if ( sessionFactory != null ) {
        sessionFactory.close();
    }

}

@Override
public void contextInitialized(ServletContextEvent arg0) {
    try {
        URL url = HibernateListener.class.getResource(path);
        config = new Configuration().configure(url);
        sessionFactory = config.buildSessionFactory();

        // save the Hibernate session factory into serlvet context
        arg0.getServletContext().setAttribute(KEY_NAME, sessionFactory);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
 Here's what I added to the web.xml
<listener>
    <listener-class>insert.package.name.here.HibernateListener</listener-class>
</listener>

No comments:

Post a Comment