posts - 0,  comments - 5,  trackbacks - 0

 

 1 import  org.apache.commons.logging.Log;
 2 import  org.apache.commons.logging.LogFactory;
 3 import  org.hibernate.FlushMode;
 4 import  org.hibernate.HibernateException;
 5 import  org.hibernate.Session;
 6 import  org.hibernate.SessionFactory;
 7 import  org.hibernate.Transaction;
 8 import  org.hibernate.cfg.Configuration;
 9
10
11
12 public   class  SessionManager  {
13      private   static  Log log  =  LogFactory.getLog(SessionManager. class );
14      private   static   final  SessionFactory sessionFactory;
15      /** 静态块:创建session factory */
16      static   {
17          try   {
18             System.out.println( " 数据映射初始化begin " );
19             Configuration configure  =   new  Configuration().configure();
20             sessionFactory  = configure.buildSessionFactory();
21              /* URL configFileURL =
22                     SessionManager.class.getResource("/hibernate.cfg.xml");
23             Configuration configure = (new Configuration()).configure(configFileURL); */

24             System.out.println( " 数据映射初始化end " );
25         }
  catch  (Throwable ex)  {
26             log.error( " Initial SessionFactory creation failed. " , ex);
27              throw   new  ExceptionInInitializerError(ex);
28         }

29     }

30      /** 获取当前线程的session对象 */
31      public   static  Session currentSession()  throws  HibernateException  {
32         Session s  =  sessionFactory.openSession();
33         s.setFlushMode(FlushMode.NEVER);
34          return  s;
35     }

36      public   static  Session currentSessionFlush()  throws  HibernateException  {
37         Session s  =  sessionFactory.openSession();
38         s.setFlushMode(FlushMode.AUTO);
39          return  s;
40     }

41      /** 关闭当前线程所在的session对象 */
42      public   static   void  closeSession(Session s)  throws  HibernateException  {
43          if  (s  !=   null ) {
44             s.close();
45         }

46     }

47      public   static  SessionFactory getSessionFactory()  {
48          if (sessionFactory != null ) {
49              return  sessionFactory;
50         }

51          else {
52             System.out.println( " 无效的factiory " );
53              return   null ;
54         }

55     }

56 }

57
posted on 2007-09-03 09:23 crazy 阅读(386) 评论(0)  编辑  收藏 所属分类: hibernate

只有注册用户登录后才能发表评论。


网站导航:
博客园   IT新闻   Chat2DB   C++博客   博问