本节主要内容:创建hibernateUtil工具类:demo
demo:
HibernateUtil.java
package hibernate_001;
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil { private static SessionFactory sessionFactory; private static Session session; static{ //1 新建配置对象 Configuration config = new Configuration().configure(); //2 新建服务注册对象 ServiceRegistry service = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //3 新建会话工厂 sessionFactory = config.buildSessionFactory(service); } //获取会话工厂 public static SessionFactory getSessionFactory(){ return sessionFactory; }
//获取会话 public static Session getSession() { session = sessionFactory.openSession(); return session; } //关闭会话 public static void closeSession(Session session){ if(session!=null){ session.close(); } }
}