码迷,mamicode.com
首页 > Web开发 > 详细

HibernateUtil

时间:2017-04-02 09:21:12      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:blog   import   figure   UI   factory   final   void   初始化   thread   

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static SessionFactory sessionFactory;

	static {
		// 创建Configuration,该对象用于读取hibernate.cfg.xml,并完成初始化
		Configuration config = new Configuration().configure();
		StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(config.getProperties());
		StandardServiceRegistry ssr = ssrb.build();
		sessionFactory = config.buildSessionFactory(ssr);
	}

	/**
	 * 获取SessionFactory
	 * 
	 * @return
	 */
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static final ThreadLocal<Session> session = new ThreadLocal<Session>();

	public static Session getCurrentSession() {
		Session s = (Session) session.get();
		if (s == null || !s.isOpen()) {
			s = sessionFactory.openSession();
			session.set(s);
		}
		return s;
	}

	public static void closeSession(Session session) {

		if (null != session) {
			session.close();
		}
	}
}

 

HibernateUtil

标签:blog   import   figure   UI   factory   final   void   初始化   thread   

原文地址:http://www.cnblogs.com/hello-daocaoren/p/6658197.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!