Storing Hibernate SessionFactory with Struts

I am starting to use Hibernate with Struts 2 for a relatively simple web project. For performance reasons, I know that it is recommended to minimize the creation time of Hibernate Configuration and SessionFactory objects.

Can someone give any input on whether this is a good way to do this or if there are more efficient approaches? I base this code on an example that I found here .

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

I notice that the example never seems to close the SessionFactory, so I added some code to contextDestroyed. Was it necessary?

Thanks so much for any input. If you can offer better examples, I would be happy to look at them. I also saw some links to the "Full Hibernate Plugin" for Struts. Is this a commonly used and best approach?

FWIW, I use Eclipse and deploy 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 is what I added in web.xml

  <listener> <listener-class>insert.package.name.here.HibernateListener</listener-class> </listener> 
+4
source share
1 answer

Your approach will work, and ServletContextListener is the right place to handle start and stop tasks for your web application. You correctly close the SessionFactory on shutdown - cleaning up after yourself is a good habit to be in.

Another thing to consider is how you create and manage your sessions. Sessions should not be shared between threads and should not be created and destroyed in each database task. It is common practice to have one session per request (often stored in ThreadLocal). This is usually called the Open Session in View template.

Personally, I am using a slightly modified version of the guice-persist extension for Google Guice.

+3
source

All Articles