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 阅读(1009) 评论(0)  编辑  收藏 所属分类: Hibernate/ibatis

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


网站导航:
 

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

常用链接

留言簿(4)

随笔分类

随笔档案

文章档案

新闻分类

新闻档案

相册

收藏夹

Java

Linux知识相关

Spring相关

云计算/Linux/虚拟化技术/

友情博客

多线程并发编程

开源技术

持久层技术相关

搜索

  •  

积分与排名

  • 积分 - 356765
  • 排名 - 154

最新评论

阅读排行榜

评论排行榜