com.heimaide.server.common.persistence.BaseDao.java Source code

Java tutorial

Introduction

Here is the source code for com.heimaide.server.common.persistence.BaseDao.java

Source

/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/free lance/infosys">infosys</a> All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.heimaide.server.common.persistence;

import com.heimaide.server.common.utils.Exceptions;
import com.heimaide.server.common.utils.ReflectHelper;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.hql.internal.ast.QueryTranslatorImpl;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * DAO?
 *
 * @param <T>
 * @author free lance
 * @version 2013-05-15
 */
public class BaseDao<T> {

    protected Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * SessionFactory
     */
    @Autowired
    private SessionFactory sessionFactory;

    /**
     * ()
     */
    private Class<?> entityClass;

    /**
     * ??
     */
    public BaseDao() {
        entityClass = ReflectHelper.getClassGenricType(getClass());
    }

    /**
     * ? Session
     */
    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * ??
     */
    public void flush() {
        getSession().flush();
    }

    /**
     * ?
     */
    public void clear() {
        getSession().clear();
    }

    public T merge(T entity) {
        return (T) getSession().merge(entity);
    }

    // -------------- QL Query --------------

    /**
     * QL 
     *
     * @param page
     * @param qlString
     * @return
     */
    public <E> Page<E> find(Page<E> page, String qlString) {
        return find(page, qlString, null);
    }

    /**
     * QL 
     *
     * @param page
     * @param qlString
     * @param parameter
     * @return
     */
    @SuppressWarnings("unchecked")
    public <E> Page<E> find(Page<E> page, String qlString, Parameter parameter) {
        // get count
        if (!page.isDisabled() && !page.isNotCount()) {
            String countQlString = "select count(*) " + removeSelect(removeOrders(qlString));
            // page.setCount(Long.valueOf(createQuery(countQlString,
            // parameter).uniqueResult().toString()));
            Query query = createQuery(countQlString, parameter);
            List<Object> list = query.list();
            if (list.size() > 0) {
                page.setCount(Long.valueOf(list.get(0).toString()));
            } else {
                page.setCount(list.size());
            }
            if (page.getCount() < 1) {
                return page;
            }
        }
        // order by
        String ql = qlString;
        if (StringUtils.isNotBlank(page.getOrderBy())) {
            ql += " order by " + page.getOrderBy();
        }
        Query query = createQuery(ql, parameter);
        // set page
        if (!page.isDisabled()) {
            query.setFirstResult(page.getFirstResult());
            query.setMaxResults(page.getMaxResults());
        }
        page.setList(query.list());
        return page;
    }

    /**
     * QL 
     *
     * @param qlString
     * @return
     */
    public <E> List<E> find(String qlString) {
        return find(qlString, null);
    }

    /**
     * QL 
     *
     * @param qlString
     * @param parameter
     * @return
     */
    @SuppressWarnings("unchecked")
    public <E> List<E> find(String qlString, Parameter parameter) {
        Query query = createQuery(qlString, parameter);
        return query.list();
    }

    /**
     * hql??sql?,?
     *
     * @param hql ??hql?
     * @return ?sql?, null, ?getResultMsg()??
     */
    public String transHqlToSql(String hql) {
        // ??session
        // session
        SessionFactoryImpl sfi = (SessionFactoryImpl) sessionFactory;
        // Query?
        QueryTranslatorImpl queryTranslator = new QueryTranslatorImpl(hql, hql, Collections.EMPTY_MAP, sfi);
        queryTranslator.compile(Collections.EMPTY_MAP, false);
        // sql
        String sql = queryTranslator.getSQLString();
        // session
        return sql;
    }

    /**
     * 2015720
     *
     * @param qlString
     * @param parameter
     * @return
     */
    @SuppressWarnings("unchecked")
    public <E> Page<E> findPage(Page<E> page, String qlString, List param) {
        // get count
        if (!page.isDisabled() && !page.isNotCount()) {
            String countQlString = "select count(*) " + removeSelect(removeOrders(qlString));
            // page.setCount(Long.valueOf(createQuery(countQlString,
            // parameter).uniqueResult().toString()));
            Query query = createQuery(countQlString, param);
            List<Object> list = query.list();
            if (list.size() > 0) {
                page.setCount(Long.valueOf(list.get(0).toString()));
            } else {
                page.setCount(list.size());
            }
            if (page.getCount() < 1) {
                return page;
            }
        }
        // order by
        String ql = qlString;
        if (StringUtils.isNotBlank(page.getOrderBy())) {
            ql += " order by " + page.getOrderBy();
        }
        Query query = createQuery(ql, param);
        // set page
        if (!page.isDisabled()) {
            query.setFirstResult(page.getFirstResult());
            query.setMaxResults(page.getMaxResults());
        }
        page.setList(query.list());
        return page;
    }

    /**
     * 2015720
     *
     * @param entityClass
     * @param propertyName
     * @param value
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> T findUniqueByProperty(Class<T> entityClass, String propertyName, Object value) {
        Assert.hasText(propertyName);
        return (T) createCriteria(entityClass, Restrictions.eq(propertyName, value)).uniqueResult();
    }

    /**
     * QL 
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<T> findAll() {
        return getSession().createCriteria(entityClass).list();
    }

    /**
     * ?
     *
     * @param id
     * @return
     */
    @SuppressWarnings("unchecked")
    public T get(Serializable id) {
        return (T) getSession().get(entityClass, id);
    }

    /**
     * ??
     *
     * @param id
     * @return
     */
    @SuppressWarnings("unchecked")
    public T getWithLock(Serializable id) {
        String hql = "from " + entityClass.getSimpleName() + " where id = :p1";
        Query query = createQuery(hql, new Parameter(id));
        query.setLockOptions(LockOptions.UPGRADE);
        return (T) query.uniqueResult();
    }

    /**
     * ?
     *
     * @param qlString
     * @return
     */
    public T getByHql(String qlString) {
        return getByHql(qlString, null);
    }

    /**
     * ?
     *
     * @param qlString
     * @param parameter
     * @return
     */
    @SuppressWarnings("unchecked")
    public T getByHql(String qlString, Parameter parameter) {
        Query query = createQuery(qlString, parameter);
        return (T) query.uniqueResult();
    }

    /**
     * 2015720 ??key value?
     *
     * @param hql
     * @param param
     * @return
     */
    public Map<Object, Object> getLinkedHashMapbyHqlQuery(String hql, Object... param) {

        Query query = getSession().createQuery(hql);
        if (param != null && param.length > 0) {
            for (int i = 0; i < param.length; i++) {
                query.setParameter(i, param[i]);
            }
        }
        List list = query.list();
        Map<Object, Object> map = new LinkedHashMap<Object, Object>();
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            Object[] tm = (Object[]) iterator.next();
            map.put(tm[0].toString(), tm[1].toString());
        }
        return map;

    }

    /**
     * ?
     *
     * @param entity
     */
    public void save(T entity) {
        try {
            // ??
            Object id = null;
            for (Method method : entity.getClass().getMethods()) {
                Id idAnn = method.getAnnotation(Id.class);
                if (idAnn != null) {
                    id = method.invoke(entity);
                    break;
                }
            }

            // ??
            if (StringUtils.isBlank((String) id)) {
                for (Method method : entity.getClass().getMethods()) {
                    PrePersist pp = method.getAnnotation(PrePersist.class);
                    if (pp != null) {
                        method.invoke(entity);
                        break;
                    }
                }
            }
            // ?
            else {
                for (Method method : entity.getClass().getMethods()) {
                    PreUpdate pu = method.getAnnotation(PreUpdate.class);
                    if (pu != null) {
                        method.invoke(entity);
                        break;
                    }
                }
            }
        } catch (IllegalArgumentException e) {
            logger.error("BaseDao:save error:" + Exceptions.getStackMsg(e));
        } catch (IllegalAccessException e) {
            logger.error("BaseDao:save error:" + Exceptions.getStackMsg(e));
        } catch (InvocationTargetException e) {
            logger.error("BaseDao:save error:" + Exceptions.getStackMsg(e));
        } catch (Exception e) {
            logger.error("BaseDao:save error:" + Exceptions.getStackMsg(e));
        }
        getSession().saveOrUpdate(entity);
    }

    /**
     * ?
     *
     * @param entityList
     */
    public void save(List<T> entityList) {
        for (T entity : entityList) {
            save(entity);
        }
    }

    /**
     * ?(flush)
     *
     * @param entityList
     */
    public void saveFlush(List<T> entityList) {
        for (T entity : entityList) {
            save(entity);
            this.getSession().flush();
        }
    }

    /**
     * 
     *
     * @param qlString
     * @return
     */
    public int update(String qlString) {
        return update(qlString, null);
    }

    /**
     * 
     *
     * @param qlString
     * @param parameter
     * @return
     */
    public int update(String qlString, Parameter parameter) {
        return createQuery(qlString, parameter).executeUpdate();
    }

    /**
     * ?
     *
     * @param id
     * @return
     */
    public int delById(Serializable id) {
        return update("delete " + entityClass.getSimpleName() + " where id = :p1", new Parameter(id));
    }

    /**
     * ?
     *
     * @return
     */
    public void delete(T entity) {
        getSession().delete(entity);
    }

    /**
     * 
     *
     * @param id
     * @return
     */
    public int deleteById(Serializable id) {
        return update("update " + entityClass.getSimpleName() + " set delFlag='" + BaseEntity.DEL_FLAG_DELETE
                + "' where id = :p1", new Parameter(id));
    }

    /**
     * 
     *
     * @param id
     * @param likeParentIds
     * @return
     */
    public int deleteById(Serializable id, String likeParentIds) {
        return update("update " + entityClass.getSimpleName() + " set delFlag = '" + BaseEntity.DEL_FLAG_DELETE
                + "' where id = :p1 or parentIds like :p2", new Parameter(id, likeParentIds));
    }

    /**
     * 
     *
     * @param id
     * @param delFlag
     * @return
     */
    public int updateDelFlag(Serializable id, String delFlag) {
        return update("update " + entityClass.getSimpleName() + " set delFlag = :p2 where id = :p1",
                new Parameter(id, delFlag));
    }

    /**
     *  QL 
     *
     * @param qlString
     * @param parameter
     * @return
     */
    public Query createQuery(String qlString, Parameter parameter) {
        Query query = getSession().createQuery(qlString);
        setParameter(query, parameter);
        return query;
    }

    /**
     * * 2015720 ??????.
     *
     * @param qlString
     * @param parameter
     * @return
     */
    public Query createQuery(String qlString, List param) {
        Query query = getSession().createQuery(qlString);
        if (param != null && param.size() > 0) {
            for (int i = 0; i < param.size(); i++) {
                query.setParameter(i, param.get(i));
            }
        }
        return query;
    }

    // -------------- SQL Query --------------

    /**
     * SQL 
     *
     * @param page
     * @param sqlString
     * @return
     */
    public <E> Page<E> findBySql(Page<E> page, String sqlString) {
        return findBySql(page, sqlString, null, null);
    }

    /**
     * SQL 
     *
     * @param page
     * @param sqlString
     * @param parameter
     * @return
     */
    public <E> Page<E> findBySql(Page<E> page, String sqlString, Parameter parameter) {
        return findBySql(page, sqlString, parameter, null);
    }

    /**
     * SQL 
     *
     * @param page
     * @param sqlString
     * @param resultClass
     * @return
     */
    public <E> Page<E> findBySql(Page<E> page, String sqlString, Class<?> resultClass) {
        return findBySql(page, sqlString, null, resultClass);
    }

    /**
     * SQL 
     *
     * @param page
     * @param sqlString
     * @param resultClass
     * @param parameter
     * @return
     */
    @SuppressWarnings("unchecked")
    public <E> Page<E> findBySql(Page<E> page, String sqlString, Parameter parameter, Class<?> resultClass) {
        return findBySql(page, sqlString, parameter, resultClass, null);
    }

    /**
     * SQL.
     */
    public Object findUniqueBySQL(String sql, Object... values) {
        return createSQLQuery(sql, values).uniqueResult();
    }

    /**
     * ??Query,???,.sql
     */
    protected Query createSQLQuery(String queryString, Object... values) {
        Assert.hasText(queryString);
        Query queryObject = getSession().createSQLQuery(queryString);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                queryObject.setParameter(i, values[i]);
            }
        }
        return queryObject;
    }

    public <E> Page<E> findBySql(Page<E> page, String sqlString, Parameter parameter, Class<?> resultClass,
            ResultTransformer rtf) {
        // get count
        if (!page.isDisabled() && !page.isNotCount()) {
            String countSqlString = "select count(*) " + removeSelect(removeOrders(sqlString));
            // page.setCount(Long.valueOf(createSqlQuery(countSqlString,
            // parameter).uniqueResult().toString()));
            Query query = createSqlQuery(countSqlString, parameter);
            List<Object> list = query.list();
            if (list.size() > 0) {
                page.setCount(Long.valueOf(list.get(0).toString()));
            } else {
                page.setCount(list.size());
            }
            if (page.getCount() < 1) {
                return page;
            }
        }
        // order by
        String sql = sqlString;
        if (StringUtils.isNotBlank(page.getOrderBy())) {
            sql += " order by " + page.getOrderBy();
        }
        SQLQuery query = createSqlQuery(sql, parameter);
        // set page
        if (!page.isDisabled()) {
            query.setFirstResult(page.getFirstResult());
            query.setMaxResults(page.getMaxResults());
        }
        if (rtf != null) {
            query.setResultTransformer(rtf);
        } else {
            setResultTransformer(query, resultClass);
        }
        page.setList(query.list());
        return page;
    }

    // 2015720?????map??????????
    // -----------------------------------------------------------------------------------------------------------------------------------
    public <E> Page<E> findPageBySql(Page<E> page, String sqlString, Class<?> resultClass, List param) {
        return queryBySql(page, sqlString, resultClass, param);
    }

    public <E> Page<E> findPageBySqlFromDB(Page<E> page, String sqlString, Class<?> resultClass, List param) {
        return queryBySqlFromDB(page, sqlString, resultClass, param);
    }

    public <E> Page<E> queryBySqlFromDB(Page<E> page, String sqlString, Class<?> resultClass, List param) {
        // get count
        if (!page.isDisabled() && !page.isNotCount()) {
            String countSqlString = "select count(*) from ( " + sqlString + ") k";// ?????
            // page.setCount(Long.valueOf(createSqlQuery(countSqlString,
            // parameter).uniqueResult().toString()));
            Query query = createSqlQuery(countSqlString, param);
            query.setCacheMode(CacheMode.REFRESH);
            List<Object> list = query.list();
            if (list.size() > 0) {
                page.setCount(Long.valueOf(list.get(0).toString()));
            } else {
                page.setCount(list.size());
            }
            if (page.getCount() < 1) {
                return page;
            }
        }
        // order by
        String sql = sqlString;
        if (StringUtils.isNotBlank(page.getOrderBy())) {
            sql += " order by " + page.getOrderBy();
        }
        SQLQuery query = createSqlQuery(sql, param);
        query.setCacheMode(CacheMode.REFRESH);
        // set page
        if (!page.isDisabled()) {
            query.setFirstResult(page.getFirstResult());
            query.setMaxResults(page.getMaxResults());
        }
        /*
         * Field[] fields = resultClass.getFields(); for (Field f : fields) {
        * query.addScalar(f.getName());// }
        */
        query.setResultTransformer(Transformers.aliasToBean(resultClass));
        page.setList(query.list());
        return page;
    }

    public <E> Page<E> queryBySql(Page<E> page, String sqlString, Class<?> resultClass, List param) {
        // get count
        if (!page.isDisabled() && !page.isNotCount()) {
            String countSqlString = "select count(*) from ( " + sqlString + ") k";// ?????
            // page.setCount(Long.valueOf(createSqlQuery(countSqlString,
            // parameter).uniqueResult().toString()));
            Query query = createSqlQuery(countSqlString, param);
            List<Object> list = query.list();
            if (list.size() > 0) {
                page.setCount(Long.valueOf(list.get(0).toString()));
            } else {
                page.setCount(list.size());
            }
            if (page.getCount() < 1) {
                return page;
            }
        }
        // order by
        String sql = sqlString;
        if (StringUtils.isNotBlank(page.getOrderBy())) {
            sql += " order by " + page.getOrderBy();
        }
        SQLQuery query = createSqlQuery(sql, param);
        // set page
        if (!page.isDisabled()) {
            query.setFirstResult(page.getFirstResult());
            query.setMaxResults(page.getMaxResults());
        }
        /*
        * Field[] fields = resultClass.getFields(); for (Field f : fields) {
        * query.addScalar(f.getName());// }
        */
        query.setResultTransformer(Transformers.aliasToBean(resultClass));
        page.setList(query.list());
        return page;
    }

    // -----------------------------------------------------------------------------------------------------------------------------------

    /**
     * SQL 
     *
     * @param sqlString
     * @return
     */
    public <E> List<E> findBySql(String sqlString) {
        return findBySql(sqlString, null, null);
    }

    /**
     * SQL 
     *
     * @param sqlString
     * @param parameter
     * @return
     */
    public <E> List<E> findBySql(String sqlString, Parameter parameter) {
        return findBySql(sqlString, parameter, null);
    }

    /**
     * SQL 
     *
     * @param sqlString
     * @param resultClass
     * @param parameter
     * @return
     */
    @SuppressWarnings("unchecked")
    public <E> List<E> findBySql(String sqlString, Parameter parameter, Class<?> resultClass) {
        return findBySql(sqlString, parameter, resultClass, null);
    }

    public <E> List<E> findBySql(String sqlString, Parameter parameter, Class<?> resultClass,
            ResultTransformer rtf) {
        SQLQuery query = createSqlQuery(sqlString, parameter);
        if (rtf != null) {
            query.setResultTransformer(rtf);
        } else {
            setResultTransformer(query, resultClass);
        }
        return query.list();
    }

    /**
     * SQL 
     *
     * @param sqlString
     * @param parameter
     * @return
     */
    public int updateBySql(String sqlString, Parameter parameter) {
        return createSqlQuery(sqlString, parameter).executeUpdate();
    }

    /**
     *  SQL 
     *
     * @param sqlString
     * @param parameter
     * @return
     */
    public SQLQuery createSqlQuery(String sqlString, Parameter parameter) {
        SQLQuery query = getSession().createSQLQuery(sqlString);
        setParameter(query, parameter);
        return query;
    }

    /**
     * 2015720 ??????.
     *
     * @param sqlString
     * @param param
     * @return
     */
    public SQLQuery createSqlQuery(String sqlString, List param) {
        SQLQuery query = getSession().createSQLQuery(sqlString);
        if (param != null && param.size() > 0) {
            for (int i = 0; i < param.size(); i++) {
                query.setParameter(i, param.get(i));
            }
        }
        return query;
    }

    /**
     * 2015720 Criteria
     *
     * @param entityClass
     * @param criterions
     * @return
     */
    private <T> Criteria createCriteria(Class<T> entityClass, Criterion... criterions) {
        Criteria criteria = getSession().createCriteria(entityClass);
        for (Criterion c : criterions) {
            criteria.add(c);
        }
        return criteria;
    }

    // -------------- Query Tools --------------

    /**
     * 
     *
     * @param query
     * @param resultClass
     */
    private void setResultTransformer(SQLQuery query, Class<?> resultClass) {
        if (resultClass != null) {
            if (resultClass == Map.class) {
                query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            } else if (resultClass == List.class) {
                query.setResultTransformer(Transformers.TO_LIST);
            } else {
                query.addEntity(resultClass);
            }
        }
    }

    /**
     * ?
     *
     * @param query
     * @param parameter
     */
    private void setParameter(Query query, Parameter parameter) {
        if (parameter != null) {
            Set<String> keySet = parameter.keySet();
            for (String string : keySet) {
                Object value = parameter.get(string);
                // ?????
                if (value instanceof Collection<?>) {
                    query.setParameterList(string, (Collection<?>) value);
                } else if (value instanceof Object[]) {
                    query.setParameterList(string, (Object[]) value);
                } else {
                    query.setParameter(string, value);
                }
            }
        }
    }

    /**
     * qlStringselect??
     *
     * @param qlString
     * @return
     */
    private String removeSelect(String qlString) {
        int beginPos = qlString.toLowerCase().indexOf("from");
        return qlString.substring(beginPos);
    }

    /**
     * hqlorderBy??
     *
     * @param qlString
     * @return
     */
    private String removeOrders(String qlString) {
        Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(qlString);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(sb, "");
        }
        m.appendTail(sb);
        return sb.toString();
    }

    // -------------- Criteria --------------

    /**
     * 
     *
     * @param page
     * @return
     */
    public Page<T> find(Page<T> page) {
        return find(page, createDetachedCriteria());
    }

    /**
     * 
     *
     * @param page
     * @param detachedCriteria
     * @return
     */
    public Page<T> find(Page<T> page, DetachedCriteria detachedCriteria) {
        return find(page, detachedCriteria, Criteria.DISTINCT_ROOT_ENTITY);
    }

    /**
     * 
     *
     * @param page
     * @param detachedCriteria
     * @param resultTransformer
     * @return
     */
    @SuppressWarnings("unchecked")
    public Page<T> find(Page<T> page, DetachedCriteria detachedCriteria, ResultTransformer resultTransformer) {
        // get count
        if (!page.isDisabled() && !page.isNotCount()) {
            page.setCount(count(detachedCriteria));
            if (page.getCount() < 1) {
                return page;
            }
        }
        Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
        criteria.setResultTransformer(resultTransformer);
        // set page
        if (!page.isDisabled()) {
            criteria.setFirstResult(page.getFirstResult());
            criteria.setMaxResults(page.getMaxResults());
        }
        // order by
        if (StringUtils.isNotBlank(page.getOrderBy())) {
            for (String order : StringUtils.split(page.getOrderBy(), ",")) {
                String[] o = StringUtils.split(order, " ");
                if (o.length == 1) {
                    criteria.addOrder(Order.asc(o[0]));
                } else if (o.length == 2) {
                    if ("DESC".equals(o[1].toUpperCase())) {
                        criteria.addOrder(Order.desc(o[0]));
                    } else {
                        criteria.addOrder(Order.asc(o[0]));
                    }
                }
            }
        }
        page.setList(criteria.list());
        return page;
    }

    /**
     * 
     *
     * @param detachedCriteria
     * @return
     */
    public List<T> find(DetachedCriteria detachedCriteria) {
        return find(detachedCriteria, Criteria.DISTINCT_ROOT_ENTITY);
    }

    /**
     * 
     *
     * @param detachedCriteria
     * @param resultTransformer
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<T> find(DetachedCriteria detachedCriteria, ResultTransformer resultTransformer) {
        Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
        criteria.setResultTransformer(resultTransformer);
        return criteria.list();
    }

    /**
     * 
     *
     * @param detachedCriteria
     * @return
     */
    @SuppressWarnings("rawtypes")
    public long count(DetachedCriteria detachedCriteria) {
        Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
        long totalCount = 0;
        try {
            // Get orders
            Field field = CriteriaImpl.class.getDeclaredField("orderEntries");
            field.setAccessible(true);
            List orderEntrys = (List) field.get(criteria);
            // Remove orders
            field.set(criteria, new ArrayList());
            // Get count
            criteria.setProjection(Projections.rowCount());
            totalCount = Long.valueOf(criteria.uniqueResult().toString());
            // Clean count
            criteria.setProjection(null);
            // Restore orders
            field.set(criteria, orderEntrys);
        } catch (NoSuchFieldException e) {
            logger.error("BaseDao:count error:" + Exceptions.getStackMsg(e));
        } catch (IllegalAccessException e) {
            logger.error("BaseDao:count error:" + Exceptions.getStackMsg(e));
        }
        return totalCount;
    }

    /**
     * ?
     *
     * @param criterions Restrictions.eq("name", value);
     * @return
     */
    public DetachedCriteria createDetachedCriteria(Criterion... criterions) {
        DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
        for (Criterion c : criterions) {
            dc.add(c);
        }
        return dc;
    }

    /**
     * ?uuid?po
     *
     * @param uuid
     * @return
     */
    public T findByUuid(String uuid) {
        List<T> list = find("from " + entityClass.getSimpleName() + " where uuid = :p1 and delFlag = 0",
                new Parameter(uuid));
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * ?uuid?po
     *
     * @param uuid
     * @return
     */
    public T findByUuidForFlag(String uuid, String delFlag) {
        List<T> list = find("from " + entityClass.getSimpleName() + " where uuid = :p1 and delFlag = :p2",
                new Parameter(uuid, delFlag));
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * ?uuid?po(??flag?)
     *
     * @param uuid
     * @return
     */
    public T findByUuidnoFlag(String uuid) {
        List<T> list = find("from " + entityClass.getSimpleName() + " where uuid = :p1 ", new Parameter(uuid));
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * @param uuidList uuid?
     * @return po
     */
    public <E> List<E> findByUuidIn(List<String> uuidList) {

        return find("from " + entityClass.getSimpleName() + " where uuid in :p1 and delFlag = 0",
                new Parameter(uuidList));
    }

    public <E> List<E> findByProperty(String property, Object value) {
        return find("from " + entityClass.getSimpleName() + " where " + property + " = :p1 and delFlag = 0",
                new Parameter(value));
    }

    /**
     * 
     */
    public void rollBack() {
        getSession().getTransaction().rollback();
    }

    /**
     * ??
     */
    public void commit() {
        getSession().getTransaction().commit();
    }

    public void evict(Object bean) {
        getSession().evict(bean);
    }
}