问题:在Hibernate中每次执行一次操做老是须要加载核心配置文件,获取链接池等等都是重复动做,因此抽取出来session
解决:工具
package com.xxx.utils; /** *Hibernate的工具类 *@author cxh */ import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HiberUtils { // 1.建立一个session回话工厂,以单例模式管理(简单的获取session第一种) private static SessionFactory sessionFactory; // 2.ThreadLocal存储session,一开始直接将session绑到当前线程,后面直接来获取线程中的session(第二种) private static ThreadLocal<Session> currentSession = new ThreadLocal<Session>(); //初始化获取session会话工厂 static { try { sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); } catch (HibernateException e){ e.printStackTrace(); throw new HibernateException("初始化会话工厂失败"); } } // 获取单例会话工厂 public static SessionFactory getSessionFactory() { return sessionFactory; } // 获取session对象 public static Session openSession() { return sessionFactory.openSession(); } // 获取绑定到线程里面的session,若是获取不到就建立一个新的线程去绑定session.这里面要想session对象的生命周期与当前线程绑定,还须要在hibernate配置文件里面配置current_session_context_class属性,设置为thread public Session getCurrentThreadSession() { // 获取线程中的session Session s = currentSession.get(); if(s == null) { // 建立一个新的session s = sessionFactory.openSession(); // 将新的session与当前线程绑定 currentSession.set(s); } // 不为空,当前线程有session,直接返回 return s; } // 关闭当前线程的session public static void closeCurrentThreadSession() { // 获取当前线程绑定的session对象 Session s = currentSession.get(); // 当前线程有session对象,且该对象不为空,须要关闭 if(s != null) { s.close(); } currentSession.set(null); } // 3.hibernate中底层已经帮你封装了将session与当前线程绑定的方法 public static Session getCurrentSession() { return sessionFactory.getCurrentSession(); } //上面两种获取线程里面的session均可以直接调用该封装方法进行关闭 public static void closeSession() throws HibernateException { sessionFactory.getCurrentSession().close(); } }