四、HibernateUtil

同一个线程的currentSession是同一个。

使用HibernateUtil可以不去hibernate.cfg.xml配置绑定信息,因为我们在代码里已经将它和本地线程绑定了(线程局部变量模式--一个变量在同一个线程里是同一个)

public class HibernateUtil {
    private static SessionFactory sessionFactory=null;
    private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
    private HibernateUtil(){
        
    }
    static{
        sessionFactory=new Configuration().configure().buildSessionFactory();
    }
    //获取全新的session
    public static Session openSession(){
        return sessionFactory.openSession();
    }
    //获取和线程关联的session
    public static Session getCurrentSession(){
        Session session=threadLocal.get();
        
        if(session==null){
            session=openSession();
            //把session设置到threadLocal相当于该session已经和线程绑定
            threadLocal.set(session);
        }
        return session;
    }
}