HIbernate 创建Session 对象

来源:互联网 发布:软件测试的发展前途 编辑:程序博客网 时间:2024/04/16 15:01

[html] view plaincopy
  1. package com.dev.hibernate;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.cfg.Configuration;  
  6. import org.hibernate.service.ServiceRegistry;  
  7. import org.hibernate.service.ServiceRegistryBuilder;  
  8.   
  9. public class HibernateUtils  
  10. {  
  11.   
  12.     private static SessionFactory factory;  
  13.   
  14.     static  
  15.     {  
  16.         Configuration cfg = new Configuration().configure();  
  17.         ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(  
  18.                 cfg.getProperties()).buildServiceRegistry();  
  19.         factory = cfg.buildSessionFactory(sr);  
  20.     }  
  21.   
  22.     public static SessionFactory getSessionFactory()  
  23.     {  
  24.         return factory;  
  25.     }  
  26.   
  27.     public static Session getSession()  
  28.     {  
  29.         return factory.openSession();  
  30.     }  
  31.   
  32.     public static void closeSession(Session session)  
  33.     {  
  34.         if (session != null)  
  35.         {  
  36.             if (session.isOpen())  
  37.             {  
  38.                 session.close();  
  39.             }  
  40.         }  
  41.     }  
  42. }  




[html] view plaincopy
  1. package com.dev.hibernate;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.cfg.Configuration;  
  6. import org.hibernate.service.ServiceRegistry;  
  7. import org.hibernate.service.ServiceRegistryBuilder;  
  8.   
  9. public class HibernateUtils  
  10. {  
  11.   
  12.     private static SessionFactory factory;  
  13.   
  14.     static  
  15.     {  
  16.         Configuration cfg = new Configuration().configure();  
  17.         ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(  
  18.                 cfg.getProperties()).buildServiceRegistry();  
  19.         factory = cfg.buildSessionFactory(sr);  
  20.     }  
  21.   
  22.     public static SessionFactory getSessionFactory()  
  23.     {  
  24.         return factory;  
  25.     }  
  26.   
  27.     public static Session getSession()  
  28.     {  
  29.         return factory.openSession();  
  30.     }  
  31.   
  32.     public static void closeSession(Session session)  
  33.     {  
  34.         if (session != null)  
  35.         {  
  36.             if (session.isOpen())  
  37.             {  
  38.                 session.close();  
  39.             }  
  40.         }  
  41.     }  
  42. }  
0 0
原创粉丝点击