Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

storing Hibernate SessionFactory with Struts

I'm getting started using Hibernate with Struts 2 for a relatively simply web project. For performance reasons, I know it is recommended to minimize the times you create the Hibernate Configuration and SessionFactory objects.

Can anyone provide some input on whether this is a good way to do it or if there are better approaches? I'm basing this code of an example I found here.

The approach is to create the SessionFactory in the contextInitialized method of the ServletContextListener and to store it in the ServletContext.

I notice the example doesn't seem to ever close the SessionFactory so I added some code in the contextDestroyed. Was this necessary?

Thanks much for any input. If you can suggest any better examples I'd be happy to look at them. I've also seen some references to a "Full Hibernate Plugin" for Struts. Is that a commonly used and better approach?

FWIW, I'm using Eclipse and deploying to Tomcat with MySQL

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>
like image 302
Justin Avatar asked Oct 12 '22 06:10

Justin


1 Answers

Your approach would work and ServletContextListeners are the right place to handle start-up and shut-down tasks for your webapp. You are correct in closing the SessionFactory at shut-down — cleaning up after yourself is a good habit to be in.

Another thing to consider is how you are creating and disposing of the sessions. Sessions should not be shared across threads nor should they be created and destroyed on every single database task. A common best practice is to have one session per request (often stored in a ThreadLocal). This is usually referred to as the Open Session in View pattern.

Personally, I use a slightly modified version of the guice-persist extension to Google Guice.

like image 87
Steven Benitez Avatar answered Oct 14 '22 03:10

Steven Benitez