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

sessionFactory的工具类

2012年09月11日 ⁄ 综合 ⁄ 共 878字 ⁄ 字号 评论关闭
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);
	}
}

从代码学知识点

抱歉!评论已关闭.