Friday, June 10, 2016

Avoiding Too Many connection of Session in hibernate using ThreadLocal class to get the current session without creating multiple times

import java.lang.ThreadLocal;
import org.hibernate.Session;

import org.hibernate.SessionFactory;
import org.hibernate.HibernateException;

public class HibernateUtil
{
    public static final ThreadLocal local = new ThreadLocal();

    // Creating Session Factory Object
    SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();

    // To get the current Session object from Session Factory object
    public static Session currentSession() throws HibernateException
    {
       Session session = (Session) local.get();

       //open a new session if this thread has no active session
       if(session == null)
       {
          session = sessionFactory.openSession();
          local.set(session);
       }

       return session;
    }
}

No comments:

Post a Comment