为了简化代码的重复性,使用HibernateUtil工具类对Hibernate有关的代码进行整合
主要实现有,getSessionFactory(),getSession(),closeSession()
public class HibernateUtil { private static final SessionFactory sessionFactory=buildSessionFactory(); private static Session session; private static SessionFactory buildSessionFactory(){ Configuration configuration=new Configuration().configure(); //实例化配置 ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();//生成服务登记 return configuration.buildSessionFactory(serviceRegistry); } //获取sessionFactory public static SessionFactory getSessionFactory(){ return sessionFactory; } //获取session public static Session getSession(){ return sessionFactory.openSession(); } //关闭session public static void closeSession(){ if(session!=null){ session.close(); } } }