HibernateUtil.java

/**
 * 
 */
package com.seavision.PermissionManage.help;

import java.sql.Connection;
import java.util.List;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * usage:
 * 
 * 
 * Session s = HibernateUtil.currentSession(); Transaction tx =
 * s.beginTransaction();
 * 
 * List l = new ArrayList();
 * 
 * ProcessBean p1= new ProcessBean("fdsfsdf"); l.add(p1); s.save(p1);
 * 
 * OperatorBean op = new OperatorBean("asdf","asdf","asdf",new Date(),"asdf",l);
 * s.save(op);
 * 
 * 
 * tx.commit(); HibernateUtil.closeSession();
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    private static final String file_name = "/hibernate_permission.cfg.xml";

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

    protected static Session session1;// hibernate会话

    protected static Transaction transaction; // hiberante事务
    // 初始化session factory
    static {
        try {

            sessionFactory = new Configuration().configure(file_name)
                    .buildSessionFactory();

        } catch (HibernateException ex) {

            throw new RuntimeException("Exception building SessionFactory: "
                    + ex.getMessage(), ex);

        }
    }

    public static final ThreadLocal session = new ThreadLocal();

    /**
     * 开始一个hibernate事务。
     */
    public static void beginTransaction() throws HibernateException {

        session1 = sessionFactory.openSession();
        transaction = session1.beginTransaction();
    }

    /**
     * 结束一个hibernate事务。
     */
    public static void endTransaction(boolean commit) throws HibernateException {

        if (commit) {
            transaction.commit();
        } else {
            // 如果是只读的操作,不需要commit这个事务。
            transaction.rollback();
        }
        session1.close();
    }

    public static String saveAndcommit(Object vo) {
        if (null == vo) {
            return Constants.FAILURE;
        }
        try {
            Session s = session1;
            s.save(vo);
        } catch (HibernateException e) {
            e.printStackTrace();
            logger.error(e);
            return Constants.FAILURE;
        } finally {
            HibernateUtil.closeSession();
        }
        return Constants.SUCCESS;
    }

    /**
     * 获取Connection
     * 
     * @return Connection
     */
    public static Connection getConnection() {

        try {
            Connection c = currentSession().connection();
            c.setAutoCommit(true);

            return c;
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取Connection
     * 
     * @return Connection
     */
    public static void closeConnection() {

        closeSession();
    }

    /**
     * 获取当前thread中得session
     * 
     * @return
     * @throws HibernateException
     */
    public static Session currentSession() throws HibernateException {
        Session s = (Session) session.get();
        // Open a new Session, if this Thread has none yet
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }

    /**
     * 关闭当前thread中得session
     * 
     * @throws HibernateException
     */
    public static void closeSession() {

        Session s = (Session) session.get();

        session.set(null);

        if (s != null)
            try {
                s.close();
            } catch (HibernateException e) {
                e.printStackTrace();
                logger.error(e);
            }

    }

    /**
     * HQL查询方法
     * 
     * @param hql
     * @return
     * @throws HibernateException
     */
    public static List queryHQL(String hql) throws HibernateException {

        return queryHQL(hql, -1, -1);

    }

    /**
     * HQL查询方法
     * 
     * @param hql
     * @return
     * @throws HibernateException
     */
    public static List queryHQL(String hql, Object[] params)
            throws HibernateException {

        return queryHQL(hql, params, -1, -1);

    }

    /**
     * HQL查询方法
     * 
     * @param hql
     * @param start
     * @param end
     * @return
     * @throws HibernateException
     */
    public static List queryHQL(String hql, int start, int end)
            throws HibernateException {

        return queryHQL(hql, null, start, end);

    }

    /**
     * 参数查询方法
     * 
     * @param hql
     *            带有参数得HQL
     * @param params
     *            参数值
     * @param start
     *            结果集中返回得开始点
     * @param end
     *            结果集中返回得中止点
     * @return List value=Object
     * @throws HibernateException
     */
    public static List queryHQL(String hql, Object[] params, int start, int end)
            throws HibernateException {

        if (null == hql) {

            return null;

        }

        String queryHQL = hql;

        Session session = HibernateUtil.currentSession();

        int begin = -1, max = -1;

        List result = null;

        if (start > 0) {
            begin = start;
        }

        if (end > start) {
            max = end - start;
        }

        Transaction tx = null;

        try {

            tx = session.beginTransaction();

            Query q = session.createQuery(queryHQL);

            if (begin > 0) {
                q.setFirstResult(begin);
            }

            if (max > 0) {
                // 为了判断是否还有数据,多输出一个记录
                q.setMaxResults(max + 1);
            }
            if (null != params) {
                for (int i = 0; i < params.length; ++i) {

                    logger.debug("-->>>>" + params[i]);

                    q.setParameter(i, params[i]);
                }
            }
            result = q.list();
            tx.commit();

        } catch (HibernateException he) {

            if (tx != null)
                tx.rollback();
            throw he;

        } finally {

            HibernateUtil.closeSession();

        }
        return result;

    }

    /**
     * add VO
     * 
     * @param vo
     * @return
     */
    public static String save(Object vo) {

        if (null == vo) {
            return Constants.FAILURE;
        }

        try {

            Session s = HibernateUtil.currentSession();

            Transaction tx = s.beginTransaction();

            s.save(vo);

            tx.commit();

        } catch (HibernateException e) {

            e.printStackTrace();
            logger.error(e);
            return Constants.FAILURE;

        } finally {
            HibernateUtil.closeSession();
        }

        return Constants.SUCCESS;
    }

    /**
     * update VO
     * 
     * @param vo
     * @return
     */
    public static String saveOrUpdate(Object vo) {

        if (null == vo) {
            return Constants.FAILURE;
        }

        try {

            Session s = HibernateUtil.currentSession();

            Transaction tx = s.beginTransaction();

            s.saveOrUpdate(vo);

            tx.commit();

        } catch (HibernateException e) {

            e.printStackTrace();
            logger.error(e);
            return Constants.FAILURE;

        } finally {
            HibernateUtil.closeSession();
        }

        return Constants.SUCCESS;
    }

    /**
     * delete VO
     * 
     * @param vo
     * @return
     */
    public static String delete(Object vo) {

        if (null == vo) {
            return Constants.FAILURE;
        }

        try {

            Session s = HibernateUtil.currentSession();

            Transaction tx = s.beginTransaction();

            s.delete(vo);

            tx.commit();

        } catch (HibernateException e) {

            // e.printStackTrace();
            logger.error("删除失败:" + vo);
            logger.error(e);
            return Constants.FAILURE;

        } finally {
            HibernateUtil.closeSession();
        }

        return Constants.SUCCESS;
    }

    public static Object getVOByID(Class cless, int id) {

        Object vo = null;

        if (-1 == id) {
            return vo;
        }

        try {

            Session s = HibernateUtil.currentSession();

            vo = s.get(cless, new Integer(id));

        } catch (HibernateException e) {

            e.printStackTrace();
            logger.error(e);

        } finally {
            HibernateUtil.closeSession();
        }

        return vo;
    }

    public static Object getVOByID(Class cless, long id) {

        Object vo = null;

        if (-1 == id) {
            return vo;
        }

        try {

            Session s = HibernateUtil.currentSession();

            vo = s.get(cless, new Long(id));

        } catch (HibernateException e) {

            e.printStackTrace();
            logger.error(e);

        } finally {
            HibernateUtil.closeSession();
        }

        return vo;
    }

    /**
     * @param objs
     */
    public static String saveAllWithTransAction(Object[] objs) {

        if (null == objs) {
            return Constants.FAILURE;
        }

        try {

            Session s = HibernateUtil.currentSession();

            Transaction tx = s.beginTransaction();
            for (int i = 0; i < objs.length; ++i) {
                s.saveOrUpdate(objs[i]);
            }

            tx.commit();

        } catch (HibernateException e) {

            e.printStackTrace();
            logger.error(e);
            return Constants.FAILURE;

        } finally {
            HibernateUtil.closeSession();
        }

        return Constants.SUCCESS;
    }

}

 

posted on 2018-08-21 13:39  让代码飞  阅读(110)  评论(0)    收藏  举报

导航

一款免费在线思维导图工具推荐:https://www.processon.com/i/593e9a29e4b0898669edaf7f?full_name=python