package fox.utils; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { public static final SessionFactory sessionFactory; static{ try{ Configuration cfg = new Configuration().configure(); sessionFactory = cfg.buildSessionFactory(); }catch(Throwable e){ System.out.println("init sessionFactory error:"+e); throw new ExceptionInInitializerError(e); } } //ThreadLocal是隔离多个线程的数据共享 //不存在多个线程之间共享资源,因此不再需要对线程同步 public static final ThreadLocal session = new ThreadLocal(); public static Session currentSession() throws HibernateException{ Session s = (Session) session.get(); if(s == null){ s = sessionFactory.openSession(); //将获得的Session变量存储在ThreadLocal变量session中 session.set(s); } return s; } public static void closeSession()throws HibernateException{ Session s = (Session) session.get(); if(s!=null){ s.close(); } session.set(null); } }
从代码学知识点