隨筆 - 6  文章 - 129  trackbacks - 0
          <2025年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          常用鏈接

          留言簿(14)

          隨筆檔案(6)

          文章分類(467)

          文章檔案(423)

          相冊

          收藏夾(18)

          JAVA

          搜索

          •  

          積分與排名

          • 積分 - 827240
          • 排名 - 49

          最新評論

          閱讀排行榜

          評論排行榜

          Hibernate 的工具類

            對于Hibernate 3.1 以前的的版本在實現(xiàn)Hibernate工具類時,需要通過兩個線程
          局部變量來保存與當(dāng)前進(jìn)行相對應(yīng)的Session和事務(wù)對象的實例.
            而對于Hibernate 3.1 以后的版本,使用線程局部變量保存Session和事務(wù)對象的
          工作就完全不需要自己去實現(xiàn)了,只需在Hibernate.cfg.xml配置文件中增加一個名為
          Current_session_context_class的屬性,并且設(shè)置該屬性的值為thread.這樣Hibernate
          就可以自動地使用線程局部變量來保存當(dāng)前的進(jìn)程的Session和事務(wù)對象了.
            相應(yīng)地,Hibernate也為其Session對象增加了getTransaction()方法,以便可以隨時
          得到當(dāng)前的事務(wù)并進(jìn)行提交或者回滾操作.這個方法在以前版本的hibernate中是不存在
          的.
          Hibernate工具類主要包括以下功能:
          (1)Hibernate的初始化操作
            這個功能不放在任何方法中,采用靜態(tài)編碼的處理方式,在對象的初始化的時候被
            調(diào)用一次就可以了.
          (2)得到當(dāng)前的配置信息
            這個方法可以得到當(dāng)前的配置信息,以便于動態(tài)進(jìn)行配置參數(shù)的修改.hibernate
            的配置信息只在Hibernate初始化的時候使用一次,在完成初始化之后對配置文件
            或者Configuration對象所做的修改將不會生效.
          (3)得到SessionFactory對象的實例
            這個方法用于得到當(dāng)前系統(tǒng)運行時的SessionFactory對象的實例,這個對象的實例
            對于整個系統(tǒng)而言是全局唯一的.
          (4)釋放各種資源
            這個方法用于終止Hibernate的報務(wù)后,釋放各種Hibernate所使用的資源.雖然這個
            方法幾乎不會用到,但對于申請資源的及時釋放是每個程序應(yīng)該掌握的基本原則.
          (5)重建SessionFactory
            由于SessionFactory對于整個Hibernate應(yīng)用是唯一的.并且是在Hibernate初始化
            之后建立好的,而且對于配置文件的修改也不會影響到已經(jīng)初始化的SessionFactory
            對象.那么如何才能使修改的配置信息對Hibernate起作用呢.這就需要重建SessionFactory
            對象實例.
          (6)攔截器注冊
            用于注冊攔截器并重建SessionFactory.
          HibenateUtil.java
          import javax.naming.InitialContext;
          import javax.naming.NamingException;

          import org.apache.commons.logging.Log;
          import org.apache.commons.logging.LogFactory;
          import org.hibernate.Interceptor;
          import org.hibernate.SessionFactory;
          import org.hibernate.cfg.Configuration;
          import org.hibernate.cfg.Environment;


          /**
           * 基礎(chǔ)的Hibernate輔助類,用于Hibernate的配置和啟動。
           * <p>
           * 通過靜態(tài)的初始化代碼來讀取Hibernate啟動參數(shù),并初始化
           * <tt>Configuration</tt>和<tt>SessionFactory</tt>對象。
           * <p>
           *
           * @author galaxy
           */
          public class HibernateUtil
          {

              private static Log log = LogFactory.getLog(HibernateUtil.class);

              // 指定定義攔截器屬性名
              private static final String INTERCEPTOR_CLASS = "hibernate.util.interceptor_class";

              // 靜態(tài)Configuration和SessionFactory對象的實例(全局唯一的)
              private static Configuration configuration;
              private static SessionFactory sessionFactory;

              static
              {
                  // 從缺省的配置文件創(chuàng)建SessionFactory
                  try
                  {
                   // 創(chuàng)建默認(rèn)的Configuration對象的實例
                   // 如果你不使用JDK 5.0或者注釋請使用new Configuration()
                   // 來創(chuàng)建Configuration()對象的實例
                      configuration = new Configuration();

                      // 讀取hibernate.properties或者h(yuǎn)ibernate.cfg.xml文件
                      configuration.configure();

                      // 如果在配置文件中配置了攔截器,那么將其設(shè)置到configuration對象中
                      String interceptorName = configuration.getProperty(INTERCEPTOR_CLASS);
                      if (interceptorName != null)
                      {
                          Class interceptorClass =
                                  HibernateUtil.class.getClassLoader().loadClass(interceptorName);
                          Interceptor interceptor = (Interceptor)interceptorClass.newInstance();
                          configuration.setInterceptor(interceptor);
                      }

                      if (configuration.getProperty(Environment.SESSION_FACTORY_NAME) != null)
                      {
                          // 讓Hibernate將SessionFacory綁定到JNDI
                          configuration.buildSessionFactory();
                      }
                      else
                      {
                          // 使用靜態(tài)變量來保持SessioFactory對象的實例
                          sessionFactory = configuration.buildSessionFactory();
                      }

                  }
                  catch (Throwable ex)
                  {
                      // 輸出異常信息
                      log.error("Building SessionFactory failed.", ex);
                      ex.printStackTrace();
                      throw new ExceptionInInitializerError(ex);
                  }
              }

              /**
               * 返回原始的Configuration對象的實例
               *
               * @return Configuration
               */
              public static Configuration getConfiguration()
              {
                  return configuration;
              }

              /**
               * 返回全局的SessionFactory對象的實例
               *
               * @return SessionFactory
               */
              public static SessionFactory getSessionFactory()
              {
                  SessionFactory sf = null;
                  String sfName = configuration.getProperty(Environment.SESSION_FACTORY_NAME);
                  if ( sfName != null)
                  {
                      log.debug("Looking up SessionFactory in JNDI.");
                      try
                      {
                          sf = (SessionFactory) new InitialContext().lookup(sfName);
                      }
                      catch (NamingException ex)
                      {
                          throw new RuntimeException(ex);
                      }
                  }
                  else
                  {
                      sf = sessionFactory;
                  }
                  if (sf == null)
                      throw new IllegalStateException( "SessionFactory not available." );
                  return sf;
              }

              /**
               * 關(guān)閉當(dāng)前的SessionFactory并且釋放所有的資源
               */
              public static void shutdown()
              {
                  log.debug("Shutting down Hibernate.");
                  // Close caches and connection pools
                  getSessionFactory().close();

                  // Clear static variables
                  configuration = null;
                  sessionFactory = null;
              }


              /**
               * 使用靜態(tài)的Configuration對象來重新構(gòu)建SessionFactory。
               */
               public static void rebuildSessionFactory()
               {
                  log.debug("Using current Configuration for rebuild.");
                  rebuildSessionFactory(configuration);
               }

              /**
               * 使用指定的Configuration對象來重新構(gòu)建SessionFactory對象。
               *
               * @param cfg
               */
               public static void rebuildSessionFactory(Configuration cfg)
               {
                  log.debug("Rebuilding the SessionFactory from given Configuration.");
                  synchronized(sessionFactory)
                  {
                      if (sessionFactory != null && !sessionFactory.isClosed())
                          sessionFactory.close();
                      if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null)
                          cfg.buildSessionFactory();
                      else
                          sessionFactory = cfg.buildSessionFactory();
                      configuration = cfg;
                  }
               }

              /**
               * 在當(dāng)前SessionFactory中注冊一個攔截器
               */
              public static SessionFactory registerInterceptorAndRebuild(Interceptor interceptor)
              {
                  log.debug("Setting new global Hibernate interceptor and restarting.");
                  configuration.setInterceptor(interceptor);
                  rebuildSessionFactory();
                  return getSessionFactory();
              }

              /**
               * 獲得攔截器對象
               *
               * @return Interceptor
               */
              public static Interceptor getInterceptor()
              {
                  return configuration.getInterceptor();
              }

              /**
               * 提交當(dāng)前事務(wù),并開始一個新的事務(wù)
               */
              public static void commitAndBeginTransaction()
              {
               sessionFactory.getCurrentSession().getTransaction().commit();
               sessionFactory.getCurrentSession().beginTransaction();
              }
          }

           



          posted on 2007-08-29 19:12 Ke 閱讀(3869) 評論(0)  編輯  收藏 所屬分類: hibernate
          主站蜘蛛池模板: 会理县| 吴旗县| 桑植县| 扎囊县| 偃师市| 八宿县| 东港市| 安义县| 沾益县| 策勒县| 海伦市| 枞阳县| 仁怀市| 丰宁| 石景山区| 台安县| 大化| 柏乡县| 井陉县| 纳雍县| 富顺县| 当涂县| 新平| 资兴市| 东乌| 桃江县| 石景山区| 社旗县| 道真| 延吉市| 安西县| 鹤岗市| 增城市| 镇安县| 临汾市| 象山县| 德安县| 兰考县| 宁南县| 澄迈县| 巫山县|