现在的位置: 首页 > 综合 > 正文

HibernateUtil

2013年09月12日 ⁄ 综合 ⁄ 共 717字 ⁄ 字号 评论关闭

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HbnUtil {
 private static SessionFactory sf;
 private static ThreadLocal local=new ThreadLocal();
 
 static{
  try {
   sf = new Configuration().configure().buildSessionFactory();
  } catch (HibernateException e) {
   e.printStackTrace();
  }
 }
 
 public static Session getSession(){
  Session s = (Session)local.get();
  if(s==null){
   if(sf!=null){
    s = sf.openSession();
   }
   local.set(s);
  }
  return s;
 }
 
 public static void closeSession(){
  Session s = (Session)local.get();
  try {
   if(s!=null && s.isOpen()){
    s.close();
   }
  } catch (HibernateException e) {
   e.printStackTrace();
  }
  local.set(null);
 }

}

抱歉!评论已关闭.