HibernateUtil
Posted 稻草人
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HibernateUtil相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章