HibernateUtil 初始化类的创建

来源:互联网 发布:js 数组转json 编辑:程序博客网 时间:2024/06/03 14:24
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 private static final ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
 //为保证线程安全,将Seeeion放到ThreadLocal中管理。这样就避免了Session的多线程共享数据的问题

 private static SessionFactory sessionFactory=null;
 static {
  try {
   Configuration cfg=new Configuration().configure();
   sessionFactory =cfg.buildSessionFactory();
  } catch (HibernateException e) {
   // TODO Auto-generated catch block
   System.out.println("创建会话工厂失败");
   e.printStackTrace();
  }
  
  
 }
 public static Session getSession() throws HibernateException{
  Session session=(Session)threadLocal.get();
  if (session==null||!session.isOpen()) {
   if (sessionFactory==null) {
    rebuildSessionFactory();
   }
   session=(sessionFactory!=null)?sessionFactory.openSession():null;
   threadLocal.set(session);//并且为了线程安全,将它放进线程锁中
  }
  
  return session;
 }
 public  static void rebuildSessionFactory() {
  // TODO Auto-generated method stub
  try {
   Configuration cfg=new Configuration().configure();
   sessionFactory=cfg.buildSessionFactory();
  } catch (HibernateException e) {
   // TODO Auto-generated catch block
   System.out.println("创建会话工厂失败");
   e.printStackTrace();
  }
  
  
 }
 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
 public static void closeSession() throws HibernateException{
  Session session=(Session)threadLocal.get();
  threadLocal.set(null);
  if (session!=null) {
   session.close();
  }
  
 }
 
}

纯粹是因为懒害羞