1 /**
2 * hibernate 工具类 用来初始化hibernate
3 *
4 * @author Home
5 *
6 */
7 public class HibernateUtil {
8
9 private static SessionFactory sessionFactory;
10 private static Session session;
11
12 static {
13 // 创建配置对象 读取hibernate.cfg.xml文件 完成初始化。
14 Configuration config = new Configuration().configure();
15 // 创建服务注册对象
16 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
17 .buildServiceRegistry();
18 // 创建会话工厂对象
19 sessionFactory = config.buildSessionFactory(serviceRegistry);
20 // 会话对象
21 session = sessionFactory.openSession();
22 }
23
24 // 获取sessionFactory
25 public static SessionFactory getSessionFactory() {
26 return sessionFactory;
27 }
28
29 // 获取session
30 public static Session getSession() {
31 return session;
32 }
33
34 // 关闭session
35 public static void closeSession(Session session) {
36 if (session != null) {
37 session.close();
38 }
39 }
40 }