ThreadLocal在hiberate中的使用

public class HibernateUtil { 
   2.        public static final SessionFactory sessionFactory; 
   3.        static { 
   4.            try { 
   5.                  sessionFactory = new Configuration().configure() 
   6.                                    .buildSessionFactory(); 
   7.            } catch (Throwable ex) { 
   8.                 throw new ExceptionInInitializerError(ex); 
   9.            } 
  10.        } 
  11.        public static final ThreadLocal session =  
  12.                                             new ThreadLocal(); 
  13.        public static Session currentSession() throws HibernateException { 
  14.                Session s = session.get(); 
  15.                if(s == null) { 
  16.                      s = sessionFactory.openSession(); 
  17.                      session.set(s); 
  18.                } 
  19.                return s; 
  20.        } 
  21.        public static void closeSession() throws HibernateException { 
  22.                 Session s = session.get(); 
  23.                 if(s != null) { 
  24.                       s.close(); 
  25.                 } 
  26.                 session.set(null); 
  27.        } 
  28. }

你可能感兴趣的:(threadLocal)