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();
}
Here is what I added in web.xml
<listener> <listener-class>insert.package.name.here.HibernateListener</listener-class> </listener>
source share