zhenghao111
9/8/2012 - 2:35 PM

hibernate-MySessionFactory

hibernate-MySessionFactory

final public class HibernateUtil {
	
	private static SessionFactory sessionFactory = null;
	private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	
	private HibernateUtil(){}
	
	static{
		sessionFactory = new Configuration().configure().buildSessionFactory();
	}
	
	//获取全新的Session
	public static Session openSession() {
		return sessionFactory.openSession();
	}
	
	//获取和线程关联的Session
	public static Session getCurrentSession() {
		Session session = threadLocal.get();
		if(session==null) {
			session = sessionFactory.openSession();
			threadLocal.set(session);
		}
		return session;
	}
}