posts - 167,  comments - 30,  trackbacks - 0

          package com.cns.certservice.dao.impl;

          import org.apache.log4j.Logger;
          import org.hibernate.HibernateException;
          import org.hibernate.Session;
          import org.hibernate.cfg.Configuration;
          import org.hibernate.SessionFactory;
          import org.hibernate.Transaction;

          import com.cns.certservice.exception.DAOException;


          public class HibernateTemplate {

              private HibernateTemplate() {

              }

              /**
               * static final session factory
               */
              private static SessionFactory sessionFactory = null;

              /**
               * local thread variable used for storing share session instance
               */
              private static final ThreadLocal localSession = new ThreadLocal();

              /**
               * log4j logger
               */
              private static final Logger logger = Logger
                      .getLogger(HibernateTemplate.class);
              /**
               * use JTA transaction
               */
              /**
               * 該工具唯一實例。
               */
              private static HibernateTemplate instance = null;
              private static Transaction tx = null;
              private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
              private static final Configuration cfg = new Configuration();
              /** Holds a single instance of Session */
              private static final ThreadLocal threadLocal = new ThreadLocal();

              /**
               * 獲取持久工具的唯一實例,以后不是使用單實例模式,而不是采用對象池支持。
               * @return PersistentTool
               * @throws BaseException
               */
              public synchronized static HibernateTemplate getInstance() {
                  if (instance == null) {
                      instance = new HibernateTemplate();
                      instance.initHibernate();
                  }
                  return instance;
              }

              /**
               * 實現Hibernate的初始化配置環境。
               */
              public void initHibernate() {
                  try {
                      //此處從系統路徑中獲取配置文件
                      cfg.configure(CONFIG_FILE_LOCATION);
                  } catch (HibernateException ex) {
                      ex.printStackTrace();
                  }
                  try {
                      // 裝載配置,構造SessionFactory對象
                      sessionFactory = cfg.buildSessionFactory();
                  } catch (HibernateException e) {
                      e.printStackTrace();
                  }
              }

              /**
               * Get the share session
               * @
               * @return Session share session
               */
              public  Session getSession() {
                  logger.debug("Now enter into getSession method of DaoUtil");
                  //obtain share session
                  Session session = (Session) localSession.get();
                  try {
                      if (session == null||!session.isOpen()) {
                          //get session by session factory
                          session = sessionFactory.openSession();
                          localSession.set(session);
                      }
                  } catch (HibernateException ex) {
                      ex.printStackTrace();

                  }
                  return session;
              }

              /**
               * Close share session
               * @
               */
              public  void close() {
                  logger.debug("Now enter into closeSessionl");
                  //obtain share session
                  Session session = (Session) localSession.get();
                  localSession.set(null);
                  if (session != null) {
                      try {
                          session.flush();
                          session.close();
                      } catch (HibernateException ex) {
                          ex.printStackTrace();

                      }
                  }
              }

              /**
               * Begin JTA transaction
               * @
               */
              public  void beginTransaction() {
                  logger.debug("Now enter into beginTransaction");
                  try {
                      Session session = (Session) localSession.get();
                      tx = session.beginTransaction();
                  } catch (Exception ex) {
                      ex.printStackTrace();

                  }
              }

              /**
               * Commit transaction
               * @
               */
              public  void commitTransaction() {
                  try {
                      tx.commit();
                  } catch (Exception ex) {
                      ex.printStackTrace();

                  }
              }

              /**
               * Rollback transaction when breaching ACID operation
               * @
               */
              public  void rollbackTransaction() {
                  try {
                      tx.rollback();
                  } catch (Exception ex) {
                      ex.printStackTrace();

                  }
              }

              /**
               * Insert a record into table
               * @param obj Object
               * @throws DAOException
               * @
               */
              public  int insertObject(Object obj) throws DAOException {
               int res = 0;
                  logger.debug("Now enter into insertObject");
                  //obtain current share session
                  try {
                      Session session = HibernateTemplate.getInstance().getSession();
                      beginTransaction();
                      Object robj = session.save(obj);
                      if (robj instanceof Integer) {
              res = (Integer) robj;
             }
                      if (robj instanceof String) {
              res =1;
             }
                      session.flush();
                  } catch (HibernateException ex) {
                      rollbackTransaction();
                      logger.error("insertObject error:", ex);
                      throw new DAOException(ex);
                  } finally {
                      commitTransaction();
                      close();
                  }
                  return res;
              }


              /**
               * Delete a record of database table by Hibernate po object
               * @param obj Object
               * @throws DAOException
               * @
               */
              public  boolean deleteObject(Object obj) throws DAOException {
               boolean res = false;
                  logger.debug("Now enter into deleteObject method");
                  //obtain current share session
                  try {
                      Session session = HibernateTemplate.getInstance().getSession();
                      beginTransaction();
                      session.delete(obj);
                      session.flush();
                      res = true;
                  } catch (HibernateException ex) {
                      rollbackTransaction();
                      logger.error("deleteObject error:", ex);
                      throw new DAOException(ex);
                  } finally {
                      commitTransaction();
                      close();
                  }
                  return res;
              }


              /**
               * Update a record of database table
               * @param ob Object
               * @throws DAOException
               * @
               */
              public  boolean updateObject(Object ob) throws DAOException {
               boolean res = false;
                  logger.debug("Now enter into updateObject");
                  //obtain current share session
                  try {
                      Session session = HibernateTemplate.getInstance().getSession();
                      beginTransaction();
                      session.update(ob);
                      session.flush();
                      res= true;
                  } catch (HibernateException ex) {
                   rollbackTransaction();
                    logger.error("updateObject error:", ex);
                    throw new DAOException(ex);
                  } finally {
                      commitTransaction();
                      close();
                  }
                  return res;
              }
          }

          posted on 2009-08-20 13:22 David1228 閱讀(1017) 評論(0)  編輯  收藏 所屬分類: Hibernate/ibatis

          <2009年8月>
          2627282930311
          2345678
          9101112131415
          16171819202122
          23242526272829
          303112345

          常用鏈接

          留言簿(4)

          隨筆分類

          隨筆檔案

          文章檔案

          新聞分類

          新聞檔案

          相冊

          收藏夾

          Java

          Linux知識相關

          Spring相關

          云計算/Linux/虛擬化技術/

          友情博客

          多線程并發編程

          開源技術

          持久層技術相關

          搜索

          •  

          積分與排名

          • 積分 - 358881
          • 排名 - 154

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 新余市| 陆丰市| 新民市| 宁安市| 莫力| 濮阳市| 蒙自县| 邯郸市| 永安市| 绥芬河市| 吉安市| 庆元县| 寿阳县| 布尔津县| 林芝县| 团风县| 甘谷县| 新龙县| 北票市| 昭通市| 三明市| 凉城县| 永定县| 遵义县| 苏尼特右旗| 休宁县| 尼玛县| 囊谦县| 嘉兴市| 化州市| 平乡县| 土默特右旗| 晋江市| 惠来县| 连州市| 宝兴县| 苍南县| 高平市| 玛曲县| 张家界市| 莱阳市|