HibernateTemplate增改删查方法

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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值