【转】HibernateDaoImpl

原文链接:https://www.javatt.com/p/96866

package com.oa.common.hibernate;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oa.common.utils.PageParam;
import com.oa.common.utils.PageUtil;
import com.oa.common.utils.StringUtil;

/**
 * 扩展HibernateDaoSupport的泛型基类
 * 
 * @param <T>
 *            实体类型
 */
@SuppressWarnings("all")
public class HibernateDaoImpl extends HibernateDaoSupport implements HibernateDao {

    /**
     * 删除对象
     * 
     * @param entity
     *            实体类
     */
    @Override
    public void delete(final Object entity) {
        getSession().delete(entity);
    }

    /**
     * 根据实体类与ID删除对象
     * 
     * @param clazz
     *            实体类
     * @param id
     *            主键ID
     */
    @Override
    public void delete(final Class<?> clazz, final Serializable id) {
        delete(get(clazz, id));
    }

    /**
     * 获取所有数据
     * 
     * @param entityClass
     *            参数T的反射类型
     */
    @Override
    public <X> List<X> getAll(final Class<X> entityClass) {
        return createCriteria(entityClass).list();
    }

    @Override
    public void save(Object transientInstance) {
        getHibernateTemplate().save(transientInstance);
    }

    @Override
    public void saveOrUpdate(Object transientInstance) {
        getHibernateTemplate().saveOrUpdate(transientInstance);
    }

    @Override
    public void update(Object transientInstance) {
        getHibernateTemplate().update(transientInstance);
    }

    @Override
    public Object merge(Object transientInstance) {
        return getHibernateTemplate().merge(transientInstance);
    }

    private boolean isNull(Serializable id) {
        if (id == null || id.toString().trim().length() < 1)
            return true;
        if (("Long".equals(id.getClass().getSimpleName()) || "Integer".equals(id.getClass().getSimpleName())) && Long.valueOf(id.toString()) == 0) {
            return true;
        }
        return false;
    }

    /**
     * 根据实体类与ID获得对象
     * 
     * @param clazz
     *            实体类
     * @param id
     *            主键ID
     */
    @Override
    public <T> T load(Class<T> entityClass, Serializable id) {
        if (isNull(id))
            return null;
        return (T) getHibernateTemplate().load(entityClass, id);
    }

    /**
     * 根据实体类与ID获得对象
     * 
     * @param clazz
     *            实体类
     * @param id
     *            主键ID
     */
    @Override
    public <T> T get(Class<T> entityClass, Serializable id) {
        if (isNull(id))
            return null;
        return (T) getHibernateTemplate().get(entityClass, id);
    }

    /**
     * HQL方式查询(不建议使用)
     * 
     * @param hql
     *            符合HQL语法的查询语句
     * @param values
     *            数量可变的条件值,按顺序绑定
     */
    public <T> List<T> queryByHQL(final String hql, final Object... values) {
        Query query = getSession().createQuery(hql);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        return (List<T>) query.list();
    }

    /**
     * HQL方式查询(建议使用)
     * 
     * @param hql
     *            符合HQL语法的查询语句
     * @param values
     */
    public <T> List<T> queryByHQL(final String hql, final Map<String, Object> params) {
        Query query = getSession().createQuery(hql);
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                query.setParameter(key, params.get(key));
            }
        }
        return (List<T>) query.list();
    }

    /**
     * SQL方式查询
     * 
     * @param sql
     *            符合SQL语法的查询语句
     * @param values
     *            数量可变的条件值,按顺序绑定
     */
    public <T> List<T> queryBySQL(final Class<T> clazz, final String sql, final Object... values) {
        SQLQuery query = getSession().createSQLQuery(sql);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        return (List<T>) query.addEntity(clazz).list();
    }

    /**
     * 根据类型创建查询对象
     * 
     * @param clazz
     *            类型
     */
    public Criteria createCriteria(final Class clazz) {
        return getSession().createCriteria(clazz);
    }

    /**
     * 对象化查询
     * 
     * @param entityClass
     *            参数T的反射类型
     * @param criterions
     *            数量可变的Criterion
     */
    public Criteria createCriteria(final Class clazz, final Criterion... criterions) {
        Criteria criteria = getSession().createCriteria(clazz);
        for (Criterion c : criterions) {
            criteria.add(c);
        }
        return criteria;
    }

    public <T> List<T> findByCriteria(final DetachedCriteria detachedCriteria) {
        return (List) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                Criteria criteria = detachedCriteria.getExecutableCriteria(session);
                criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
                return criteria.list();
            }
        });
    }

    // 用于分页处理
    public <T> List<T> findByCriteria(final DetachedCriteria detachedCriteria, final int pageSize, final int currentPage) {
        // 返回记录总数
        int total = this.findRowCountByCriteria(detachedCriteria);
        return (List) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                Criteria criteria = detachedCriteria.getExecutableCriteria(session);
                if (pageSize > 0) {
                    criteria.setMaxResults(pageSize);
                }

                if (currentPage > 0) {
                    criteria.setFirstResult(currentPage);
                }
                criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
                return criteria.list();
            }
        });
    }

    // 用于分页处理
    public List findByCriteriaPage(final DetachedCriteria detachedCriteria, final int pageSize, final int currentPage) {
        return (List) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                Criteria criteria = detachedCriteria.getExecutableCriteria(session);
                if (pageSize > 0) {
                    criteria.setFirstResult((currentPage - 1) * pageSize);
                    criteria.setMaxResults(pageSize);
                }
                criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
                return criteria.list();
            }
        });
    }

    @Override
    public <T> T findOne(final String hql, final Object... params) {
        return (T) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query hqlQuery = session.createQuery(hql);
                if (params != null) {
                    for (int i = 0; i < params.length; i++) {
                        hqlQuery.setParameter(i, params[i]);
                    }
                }
                return hqlQuery.setMaxResults(1).uniqueResult();
            }
        });
    }

    public <T> T findOneCache(final String hql, final Object... params) {
        return (T) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query hqlQuery = session.createQuery(hql).setCacheable(true);
                if (params != null) {
                    for (int i = 0; i < params.length; i++) {
                        hqlQuery.setParameter(i, params[i]);
                    }
                }
                return hqlQuery.setMaxResults(1).uniqueResult();
            }
        });
    }

    @Override
    public <T> T findOneSql(final String sql, final Class<T> entityClass, final Object... params) {
        return (T) getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session arg0) throws HibernateException, SQLException {
                SQLQuery sqlQuery = arg0.createSQLQuery(sql);
                if (params != null) {
                    for (int i = 0; i < params.length; i++) {
                        sqlQuery.setParameter(i, params[i]);
                    }
                }
                if (entityClass != null) {
                    if (Map.class.getName().equals(entityClass.getName())) {
                        sqlQuery.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
                    } else {
                        sqlQuery.addEntity(entityClass);
                    }
                }
                return sqlQuery.setMaxResults(1).uniqueResult();
            }
        });
    }

    @Override
    public <T> List<T> findBySql(final String sql, final Class<T> entityClass, final Object... params) {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session arg0) throws HibernateException, SQLException {
                SQLQuery sqlQuery = arg0.createSQLQuery(sql);
                if (params != null) {
                    for (int i = 0; i < params.length; i++) {
                        sqlQuery.setParameter(i, params[i]);
                    }
                }
                if (entityClass != null) {
                    if (Map.class.getName().equals(entityClass.getName())) {
                        sqlQuery.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
                    } else {
                        sqlQuery.addEntity(entityClass);
                    }
                }
                return sqlQuery.list();
            }
        });
    }

    public int findRowCountByCriteria(final DetachedCriteria detachedCriteria) {
        return ((Integer) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                Criteria criteria = detachedCriteria.getExecutableCriteria(session);
                Integer totalCount = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
                criteria.setProjection(null);
                return Integer.valueOf((totalCount == null) ? 0 : totalCount.intValue());
            }
        })).intValue();
    }

    public <T> List<T> findByProjectionDetachedCriteria(final DetachedCriteria detachedCriteria) {
        return (List) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                Criteria criteria = detachedCriteria.getExecutableCriteria(session);
                criteria.setResultTransformer(CriteriaSpecification.PROJECTION);
                return criteria.list();
            }
        });
    }

    @Override
    public <E> void deleteCollection(Collection<E> objs) {
        getHibernateTemplate().deleteAll(objs);
    }

    @Override
    public Integer executeSql(final String sql, final Object... params) {
        return (Integer) getHibernateTemplate().execute(new HibernateCallback() {

            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery(sql);
                if (params != null) {
                    for (int i = 0; i < params.length; i++) {
                        query.setParameter(i, params[i]);
                    }
                }
                return query.executeUpdate();
            }
        });
    }

    @Override
    public <T> List<T> exeHqlList(String hql, int pageSize, int currentPage) {
        Query query = getSession().createQuery(hql);
        if (pageSize > 0) {
            query.setFirstResult((currentPage - 1) * pageSize);
            query.setMaxResults(pageSize);
        }
        query.setCacheable(true);
        return query.list();
    }

    @Override
    public <E> void saveOrUpdate(Collection<E> objs) {
        getHibernateTemplate().saveOrUpdateAll(objs);
    }

    @Override
    public void updateHqlQuery(String hql) {
        Query query = getSession().createQuery(hql);
        query.setCacheable(true);
        query.executeUpdate();
    }

    @Override
    public <X> List<X> findByHql(String hql, Object... params) {
        return (List<X>) getHibernateTemplate().find(hql, params);
    }

    @Override
    public <T> T execute(final String hql, final Object... params) {
        return (T) getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createQuery(hql);
                if (params != null) {
                    for (int i = 0; i < params.length; i++) {
                        query.setParameter(i, params[i]);
                    }
                }
                return query.executeUpdate();
            }
        });
    }

    @Override
    public List findPageBySql(final String sql, final Map<String, Object> sqlParamMap) {
        final PageParam pageParam = PageUtil.getPageParam();
        // 计算总算
        if (!StringUtil.required(pageParam.getTotalSql())) {
            int index = PageUtil.indexOf(sql.toLowerCase(), " from ");
            int endIndex = PageUtil.indexOf(sql.toLowerCase(), " order ");
            if (endIndex == -1) {
                endIndex = sql.length();
            }
            pageParam.setTotalSql("select count(*) " + sql.substring(index, endIndex));
        }
        pageParam.setTotalRow((Integer) this.getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery(pageParam.getTotalSql());
                if (sqlParamMap != null && sqlParamMap.size() > 0) {
                    query.setProperties(sqlParamMap);
                }
                return StringUtil.toInt(query.setProperties(sqlParamMap).uniqueResult());
            }
        }));
        // 分页数据
        return this.getHibernateTemplate().executeFind(new HibernateCallback() {
            @Override
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                SQLQuery query = session.createSQLQuery(pageParam.getOrderBy(sql));
                if (sqlParamMap != null && sqlParamMap.size() > 0) {
                    query.setProperties(sqlParamMap);
                }
                if (pageParam.getEntityClass() != null) {
                    query.addEntity(pageParam.getEntityClass());
                } else {
                    // 预设为MAP
                    query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
                }
                return query.setFirstResult(pageParam.getCurrRowNum()).setMaxResults(pageParam.getPageSize()).list();
            }
        });
    }

    @Override
    public List findPageByHql(final String hql, final Object... conditions) {
        final PageParam pageParam = PageUtil.getPageParam();
        // 计算总算
        int total = 0;

        int index = -1;
        if (hql.matches("(?i)^\\s*select\\b.*")) {
            index = hql.toLowerCase().indexOf(" from ");
        }
        int endIndex = hql.toLowerCase().lastIndexOf(" order ");
        if (index == -1) {
            index = 0;
        }
        if (endIndex == -1) {
            endIndex = hql.length();
        }
        List l = this.getHibernateTemplate().find("select count(*) " + hql.substring(index, endIndex).replaceAll("\\bfetch\\b", ""), conditions);
        if (l != null && l.size() > 0) {
            total = StringUtil.toInt(l.get(0));
        }
        pageParam.setTotalRow(total);
        // 分页数据
        return this.getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createQuery(pageParam.getOrderBy(hql));
                if (conditions != null && conditions.length > 0) {
                    for (int i = conditions.length - 1; i >= 0; i--) {
                        query.setParameter(i, conditions[i]);
                    }
                }
                return query.setFirstResult(pageParam.getCurrRowNum()).setMaxResults(pageParam.getPageSize()).list();
            }
        });
    }

    @Override
    public <X> List<X> findByHqlCache(final String hql, final Object... params) {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query hqlQuery = session.createQuery(hql).setCacheable(true);
                if (params != null) {
                    for (int i = 0; i < params.length; i++) {
                        hqlQuery.setParameter(i, params[i]);
                    }
                }
                return hqlQuery.list();
            }
        });
    }

    @Override
    public void executeLocalSql(String sql) {
        getSession().createSQLQuery(sql).executeUpdate();
    }
}
posted @ 2020-09-18 08:49  伊贺双刀流  阅读(295)  评论(0编辑  收藏  举报