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 {Here's what I added to the web.xml
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());
}
}
<listener>
<listener-class>insert.package.name.here.HibernateListener</listener-class>
</listener>
No comments:
Post a Comment