Quantcast
Channel: Java Programming Forum - Learn Java Programming - Hibernate
Viewing all articles
Browse latest Browse all 76

How to access SessionFactory instance stored in SerlvetContextListener class

$
0
0
I want my hibernate SessionFactory instance to be loaded when my application is deployed so I created a class named HibernateContext.

Code:

package org.LMS.Model;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class HibernateContext implements ServletContextListener{

        SessionFactory sessionFactory;
        @Override
        public void contextDestroyed(ServletContextEvent arg0)
        {
                sessionFactory = new Configuration ().configure ().buildSessionFactory ();
        }

        @Override
        public void contextInitialized(ServletContextEvent arg0)
        {
                sessionFactory.close();               
        }

}//end HibernateContext class

I configured my web.xml file to reflect this change.
Code:

<!-- HibernateContext Listener Mapping -->
  <listener>
          <listener-class>org.LMS.Model.HibernateContext</listener-class>
  </listener>

My problem is that how can is access the SessionFactory throughout my application from the HibernateContext class.Please tell me if there
is a better way of accomplishing this.

Viewing all articles
Browse latest Browse all 76

Trending Articles