Hibernate的一个帮助类----------感觉写得比较好,有参考价值,果断备份下来……
1 package cn.zj.qiao.utils; 2 3 import org.hibernate.HibernateException; 4 import org.hibernate.Session; 5 import org.hibernate.SessionFactory; 6 import org.hibernate.cfg.Configuration; 7 import org.hibernate.service.ServiceRegistry; 8 import org.hibernate.service.ServiceRegistryBuilder; 9 10 public class HibernateUtil { 11 public static final SessionFactory sessionFactory ; 12 public static final ThreadLocal<Session> session = new ThreadLocal<Session>(); 13 static{ 14 try{ 15 //create the sessionFactory from hibernate.cfg.xml 16 Configuration cf = new Configuration().configure(); 17 ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cf.getProperties()).buildServiceRegistry(); 18 sessionFactory = cf.buildSessionFactory(sr); 19 }catch(Throwable e){ 20 System.err.println("inital SessionFactory creation failed. " + e); 21 throw new ExceptionInInitializerError(e); 22 } 23 } 24 25 public static Session currrentSession()throws HibernateException{ 26 Session s = (Session)session.get(); 27 if(s == null){ 28 s = sessionFactory.openSession(); 29 session.set(s); 30 } 31 32 return s; 33 } 34 35 public static void closeSession()throws HibernateException{ 36 Session s = (Session)session.get(); 37 if(s != null){ 38 s.close(); 39 session.set(null); 40 } 41 } 42 }
人生最可贵的事情是sb似的坚持于追求……