com.zhumeng.dream.orm.hibernate.HibernateDao.java Source code

Java tutorial

Introduction

Here is the source code for com.zhumeng.dream.orm.hibernate.HibernateDao.java

Source

/**
 * Copyright (c) 2005-2010 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: HibernateDao.java 1205 2010-09-09 15:12:17Z calvinxiu $
 */
package com.zhumeng.dream.orm.hibernate;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Entity;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.compass.gps.device.hibernate.HibernateSyncTransactionFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.impl.CriteriaImpl;
import org.hibernate.property.ChainedPropertyAccessor;
import org.hibernate.property.PropertyAccessor;
import org.hibernate.property.PropertyAccessorFactory;
import org.hibernate.property.Setter;
import org.hibernate.transform.ResultTransformer;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.zhumeng.dream.orm.Page;
import com.zhumeng.dream.orm.PropertyFilter;
import com.zhumeng.dream.orm.PropertyFilter.MatchType;
import com.zhumeng.dream.orm.QueryResult;
import com.zhumeng.dream.util.bean.SQLColumnToBean;
import com.zhumeng.dream.util.others.ClassUtils;
import com.zhumeng.dream.util.reflection.ReflectionUtils;

/**
 * ?SpringSideHibernat DAO.
 * 
 * ,?.
 * ?Service,?DAO?,?.
 * 
 * @param <T> DAO?
 * @param <PK> 
 * 
 * @author calvin
 */
public class HibernateDao<T, PK extends Serializable> extends SimpleHibernateDao<T, PK> {

    /**
     * Dao?.
     * ??Class.
     * eg.
     * public class UserDao extends HibernateDao<User, Long>{
     * }
     */
    public HibernateDao() {
        super();
    }

    /**
     * ?Dao, ServiceHibernateDao.
     * Class.
     * eg.
     * HibernateDao<User, Long> userDao = new HibernateDao<User, Long>(sessionFactory, User.class);
     */
    public HibernateDao(final SessionFactory sessionFactory, final Class<T> entityClass) {
        super(sessionFactory, entityClass);
    }

    //--  --//

    /**
     * ?.
     */
    public Page<T> getAll(final Page<T> page) {
        return findPage(page);
    }

    /**
     * HQL.
     * 
     * @param page ?. ???orderBy?.
     * @param hql hql?.
     * @param values ????,?.
     * 
     * @return , ??.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public Page<T> findPage(final Page<T> page, final String hql, final Object... values) {
        Assert.notNull(page, "page?");

        Query q = createQuery(hql, values);

        if (page.isAutoCount()) {
            long totalCount = countHqlResult(hql, values);
            page.setTotalCount(totalCount);
        }

        setPageParameterToQuery(q, page);

        List result = q.list();
        page.setResult(result);
        return page;
    }

    /**
     * HQL.
     * 
     * @param page ?. ???orderBy?.
     * @param hql hql?.
     * @param values ???,??.
     * 
     * @return , ??.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public Page<T> findPage(final Page<T> page, final String hql, final Map<String, ?> values) {
        Assert.notNull(page, "page?");

        Query q = createQuery(hql, values);

        if (page.isAutoCount()) {
            long totalCount = countHqlResult(hql, values);
            page.setTotalCount(totalCount);
        }

        setPageParameterToQuery(q, page);

        List result = q.list();
        page.setResult(result);
        return page;
    }

    /**
     * Criteria.
     * 
     * @param page ?.
     * @param criterions ???Criterion.
     * 
     * @return .??.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public Page<T> findPage(final Page<T> page, final Criterion... criterions) {
        Assert.notNull(page, "page?");

        Criteria c = createCriteria(criterions);

        if (page.isAutoCount()) {
            long totalCount = countCriteriaResult(c);
            page.setTotalCount(totalCount);
        }

        setPageParameterToCriteria(c, page);

        List result = c.list();
        page.setResult(result);
        return page;
    }

    /**
     * Criteria.
     * 
     * @param page ?.
     * @param criterions ???Criterion.
     * 
     * @return .??.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public Page<T> findPage(final Page<T> page, final String[] aliasBeans, final Criterion... criterions) {
        Assert.notNull(page, "page?");

        Criteria c = createCriteria(criterions);
        c = createAlias(c, aliasBeans);

        if (page.isAutoCount()) {
            long totalCount = countCriteriaResult(c);
            page.setTotalCount(totalCount);
        }

        setPageParameterToCriteria(c, page);

        List result = c.list();
        page.setResult(result);
        return page;
    }

    /**
     * ?Query,.
     */
    protected Query setPageParameterToQuery(final Query q, final Page<T> page) {

        Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

        //hibernatefirstResult??0
        q.setFirstResult(page.getFirst() - 1);
        q.setMaxResults(page.getPageSize());
        return q;
    }

    /**
     * ?Criteria,.
     */
    protected Criteria setPageParameterToCriteria(final Criteria c, final Page<T> page) {

        //Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

        if (page.getFirst() != -1 && page.getPageSize() != -1) {
            //hibernatefirstResult??0
            c.setFirstResult(page.getFirst() - 1);
            c.setMaxResults(page.getPageSize());
        }

        if (page.isOrderBySetted()) {
            String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
            String[] orderArray = StringUtils.split(page.getOrder(), ',');

            Assert.isTrue(orderByArray.length == orderArray.length,
                    "???,????");

            for (int i = 0; i < orderByArray.length; i++) {
                if (Page.ASC.equals(orderArray[i])) {
                    c.addOrder(Order.asc(orderByArray[i]));
                } else {
                    c.addOrder(Order.desc(orderByArray[i]));
                }
            }
        }
        return c;
    }

    /**
     * countHql.
     * 
     * ???hql?,??hql?count?.
     */
    protected long countHqlResult(final String hql, final Object... values) {
        String countHql = prepareCountHql(hql);

        try {
            Long count = findUnique(countHql, values);
            return count;
        } catch (Exception e) {
            throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
        }
    }

    /**
     * countHql.
     * 
     * ???hql?,??hql?count?.
     */
    protected long countHqlResult(final String hql, final Map<String, ?> values) {
        String countHql = prepareCountHql(hql);

        try {
            Long count = findUnique(countHql, values);
            return count;
        } catch (Exception e) {
            throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
        }
    }

    private String prepareCountHql(String orgHql) {
        String fromHql = orgHql;
        //select??order by???count,?.
        fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
        fromHql = StringUtils.substringBefore(fromHql, "order by");

        String countHql = "select count(*) " + fromHql;
        return countHql;
    }

    /**
     * countCriteria.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    protected long countCriteriaResult(final Criteria c) {
        CriteriaImpl impl = (CriteriaImpl) c;

        // Projection?ResultTransformer?OrderBy??,??Count?
        Projection projection = impl.getProjection();
        ResultTransformer transformer = impl.getResultTransformer();

        List<CriteriaImpl.OrderEntry> orderEntries = null;
        try {
            orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries");
            ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());
        } catch (Exception e) {
            logger.error("??:{}", e.getMessage());
        }

        // Count
        Long totalCountObject = 0l;
        try {
            totalCountObject = (Long) c.setProjection(Projections.rowCount()).uniqueResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        long totalCount = (totalCountObject != null) ? totalCountObject : 0;

        // ?Projection,ResultTransformerOrderBy??
        c.setProjection(projection);

        if (projection == null) {
            c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
        }
        if (transformer != null) {
            c.setResultTransformer(transformer);
        }
        try {
            ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
        } catch (Exception e) {
            logger.error("??:{}", e.getMessage());
        }

        return totalCount;
    }

    //-- ?(PropertyFilter) --//

    /**
     * ,????.
     * 
     * @param matchType ??,????PropertyFilterMatcheType enum.
     */
    public List<T> findBy(final String propertyName, final Object value, final MatchType matchType) {
        Criterion criterion = buildCriterion(propertyName, value, matchType);
        return find(criterion);
    }

    /**
     * ?.
     */
    public List<T> find(List<PropertyFilter> filters) {
        Criterion[] criterions = buildCriterionByPropertyFilter(filters);
        return find(criterions);
    }

    /**
     * ?.
     */
    public Long countResult(List<PropertyFilter> filters) {
        Criterion[] criterions = buildCriterionByPropertyFilter(filters);
        Criteria c = createCriteria(criterions);
        return countCriteriaResult(c);
    }

    /**
     * add by wucong
     * ?  ?
     * @param filters
     * @param orderByProperty
     * @param isAsc
     * @return
     */
    public List<T> find(List<PropertyFilter> filters, String orderByProperty, boolean isAsc) {
        Criterion[] criterions = buildCriterionByPropertyFilter(filters);
        return find(orderByProperty, isAsc, criterions);
    }

    /**
     * ?.
     * ??
     */
    public List<T> find(List<PropertyFilter> filters, final String[] alias) {
        Criterion[] criterions = buildCriterionByPropertyFilter(filters);
        return find(alias, criterions);
    }

    /**
     * ?.
     */
    public Page<T> findPage(final Page<T> page, final List<PropertyFilter> filters) {
        Criterion[] criterions = buildCriterionByPropertyFilter(filters);
        return findPage(page, criterions);
    }

    /**
     * ?.
     *   ??
     */
    public Page<T> findPage(final Page<T> page, final List<PropertyFilter> filters, final String[] aliasBeans) {

        Criterion[] criterions = buildCriterionByPropertyFilter(filters);

        return findPage(page, aliasBeans, criterions);
    }

    /**
     * ??Criterion,.
     */
    protected Criterion buildCriterion(final String propertyName, final Object propertyValue,
            final MatchType matchType) {
        Assert.hasText(propertyName, "propertyName?");
        Criterion criterion = null;
        //?MatchTypecriterion
        switch (matchType) {
        case EQ:
            criterion = Restrictions.eq(propertyName, propertyValue);
            break;
        case LIKE:
            criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.ANYWHERE);
            break;
        case LIKEEXACT:
            criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.EXACT);
            break;
        case LIKESTART:
            criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.START);
            break;
        case LIKEEND:
            criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.END);
            break;
        case LE:
            criterion = Restrictions.le(propertyName, propertyValue);
            break;
        case LT:
            criterion = Restrictions.lt(propertyName, propertyValue);
            break;
        case GE:
            criterion = Restrictions.ge(propertyName, propertyValue);
            break;
        case GT:
            criterion = Restrictions.gt(propertyName, propertyValue);
            break;
        case NEQ:
            criterion = Restrictions.ne(propertyName, propertyValue);
            break;
        case ISN:
            criterion = Restrictions.isNull(propertyName);
            break;
        case ISNN:
            criterion = Restrictions.isNotNull(propertyName);
            break;
        case IN:
            criterion = Restrictions.in(propertyName, (Object[]) propertyValue);
            break;

        }
        return criterion;
    }

    /**
     * ?Criterion,.
     */
    protected Criterion[] buildCriterionByPropertyFilter(final List<PropertyFilter> filters) {
        List<Criterion> criterionList = new ArrayList<Criterion>();
        for (PropertyFilter filter : filters) {
            /*if (!filter.hasMultiProperties()) { //??.
               Criterion criterion = buildCriterion(filter.getPropertyName(), filter.getMatchValue(), filter
              .getMatchType());
               criterionList.add(criterion);
            } else {//??,or?.
               Disjunction disjunction = Restrictions.disjunction();
               for (String param : filter.getPropertyNames()) {
                  Criterion criterion = buildCriterion(param, filter.getMatchValue(), filter.getMatchType());
                  disjunction.add(criterion);
               }
               criterionList.add(disjunction);
            }*/
            //update by wucong
            //  System.out.println("+++++++++++++++++++++++++++++++++++++++filter:"+filter);
            if (filter == null)
                continue;
            if (!filter.hasMultiProperties()) { //??.
                Disjunction disjunction = Restrictions.disjunction();
                for (Object matchValue : filter.getMatchValues()) {
                    Criterion criterion = buildCriterion(filter.getPropertyName(), matchValue,
                            filter.getMatchType());
                    disjunction.add(criterion);
                }
                criterionList.add(disjunction);
            } else {//??,or?.
                Disjunction disjunction = Restrictions.disjunction();
                for (String param : filter.getPropertyNames()) {
                    for (Object matchValue : filter.getMatchValues()) {
                        Criterion criterion = buildCriterion(param, matchValue, filter.getMatchType());
                        disjunction.add(criterion);
                    }
                }
                criterionList.add(disjunction);
            }
        }
        //?
        //      criterionList.add(Restrictions.gt("status", -100) );
        return criterionList.toArray(new Criterion[criterionList.size()]);
    }

    /**
     * ?? 
     * @author:lizhong
     * @param <T>
     * @param firstIndex  
     * @param maxResult ?? 'maxResult''firstIndex''-1',?.
     * @param wheresql where??,???where,???param1
     * :" o.username= :param1 and o.email= param2....."
     * @param params where????.
     * @param orderBy ?sql?orderby ?,map?key??,????(desc or asc)
     * @return
     */
    @SuppressWarnings("unchecked")
    public QueryResult<T> getScrollData(int firstIndex, int maxResult, String wheresql, Object[] params,
            LinkedHashMap<String, String> orderBy) {
        String where = wheresql == null || "".equals(wheresql.trim()) ? "" : " where " + wheresql;
        String entityName = entityClass.getName();
        String hql = "select o from " + entityName + " o " + where + buildOrderby(orderBy);
        Query query = getSession().createQuery(hql);
        setQueryParam(query, params);
        if (firstIndex != -1 && maxResult != -1) {
            query.setFirstResult(firstIndex).setMaxResults(maxResult);
        }
        QueryResult<T> qr = new QueryResult<T>();
        qr.setResultList(query.list());
        query = getSession()
                .createQuery("select count(" + getCountField(entityClass) + ") from " + entityName + " o " + where);
        setQueryParam(query, params);
        qr.setTotalRecord((Long) query.uniqueResult());
        return qr;
    }

    /**
     * ??,?,??.
     * @author:lizhong
     * @param firstIndex
     * @param maxResult ??
     * @param orderBy ?sql?orderby ?,map?key??,????(desc or asc)
     * @return
     */
    public QueryResult<T> getScrollData(int firstIndex, int maxResult, LinkedHashMap<String, String> orderBy) {
        return getScrollData(firstIndex, maxResult, null, null, orderBy);
    }

    /**
     * ??,?,??
     * @author:lizhong
     * @param <T>
     * @param firstIndex 
     * @param maxResult ??
     * @param wheresql where??,???where,???param1
     * :" o.username= :param1 and o.email= param2....."
     * @param params where????.
     * @return
     */
    public QueryResult<T> getScrollData(int firstIndex, int maxResult, String wheresql, Object[] params) {
        return getScrollData(firstIndex, maxResult, wheresql, params, null);

    }

    /**
     * ??.
     * @author:lizhong
     * @param <T>
     * @param firstIndex 
     * @param maxResult ??
     * @return
     */
    public QueryResult<T> getScrollData(int firstIndex, int maxResult) {
        return getScrollData(firstIndex, maxResult, null, null, null);
    }

    /**
     * ??
     * @author:lizhong
     *
     */
    public QueryResult<T> getScrollData() {
        return getScrollData(-1, -1);
    }

    /**
      * ?? ??
      * @author            : lizhong
       * @param wheresql    : where??,???where,???param1,:" o.username= :param1 and o.email= param2....."
       * @param params      : where????.
       * @param orderBy     : ?sql?orderby ?,map?key??,????(desc or asc)
      * @return
     */
    public QueryResult<T> getScrollData(String wheresql, Object[] params, LinkedHashMap<String, String> orderBy) {
        return getScrollData(-1, -1, wheresql, params, orderBy);
    }

    /**
     * order by? :order by o.email desc , o.username asc
     * @author: lizhong
     * @param orderBy key , valuedesc/asc.:
     * orderBy.put("email", "desc");
     * orderBy.put("username", "asc");
     * ?sql?order by o.email desc,o.username asc
     * @return
     */

    public static String buildOrderby(LinkedHashMap<String, String> orderBy) {
        StringBuilder order = new StringBuilder();
        if (orderBy != null && orderBy.size() > 0) {
            order.append(" order by ");
            for (Entry<String, String> entry : orderBy.entrySet()) {
                order.append(" o.").append(entry.getKey()).append(" ").append(entry.getValue()).append(",");
            }
            order.deleteCharAt(order.length() - 1);
        }
        return order.toString();
    }

    /**
     * where???,??1.:where o.username=?1 and o.email=?2 
     * @author: lizhong
     * @param query 
     * @param params ?
     */
    public static void setQueryParam(Query query, Object[] params) {
        String param = "";
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                param = "param" + (i + 1);
                query.setParameter(param, params[i]);
            }
        }
    }

    /**
     * ?,hibernate???select count(o) from Xxx o?BUG,
     * hibernatejpql??sqlselect count(field1,field2,...),count()
     * ??HQL?:"select count(*) from Object"
     * @author: lizhong
     * @param <E>
     * @param clazz
     * @return
     */
    protected static <E> String getCountField(Class<E> clazz) {
        String out = "o";
        try {
            PropertyDescriptor[] propertys = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
            for (PropertyDescriptor property : propertys) {
                Method method = property.getReadMethod();
                if (method != null && method.isAnnotationPresent(EmbeddedId.class)) {
                    PropertyDescriptor[] props = Introspector.getBeanInfo(property.getPropertyType())
                            .getPropertyDescriptors();
                    out = "o." + property.getName() + "."
                            + (!props[1].getName().equals("class") ? props[1].getName() : props[0].getName());
                    break;
                }
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        return out;
    }

    /**
     * (detached)
     */
    @SuppressWarnings("unchecked")
    public List<T> find(DetachedCriteria query) {
        return query.getExecutableCriteria(this.getSession()).list();
    }

    /**
     * (detached)
     */
    @SuppressWarnings("unchecked")
    public List<T> find(DetachedCriteria query, int firstIndex, int maxResult) {
        return query.getExecutableCriteria(this.getSession()).setFirstResult(firstIndex).setMaxResults(maxResult)
                .list();
    }

    public List<T> execList(String hql, List<Object> values) {
        Assert.hasText(hql, "queryString?");
        Query query = getSession().createQuery(hql);
        if (values != null) {
            int i = 0;
            for (Object obj : values)
                query.setParameter(i++, obj);
        }
        return query.list();
    }

    /*
     * add by wucong
     * sql
     */
    public Page<T> findPageBySql(final Page<T> page, final String sql, final Object... values) {
        Assert.notNull(page, "page?");
        /*
         * sqlorderBy ?,order by ????
         * 
         * sql??????
         */
        Query q = createSqlQuery(sql, values);
        if (page.isAutoCount()) {
            long totalCount = countSqlResult(sql, values);
            page.setTotalCount(totalCount);
        }

        setPageParameterToSqlQuery(q, page);

        List result = q.list();
        page.setResult(result);
        return page;
    }

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

    /*
     * sql?
     */
    public Query createSqlQuery(final String queryString, final Object... values) {
        Assert.hasText(queryString, "queryString?");
        Query query = getSession().createSQLQuery(queryString).addEntity(entityClass);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        return query;
    }

    /*
     * sql
     */
    protected long countSqlResult(final String sql, final Object... values) {
        String countSql = prepareCountSql(sql);
        BigDecimal count = findUniqueBySql(countSql, values);
        return count.longValue();
    }

    /*
     * sql??
     */
    private String prepareCountSql(String orgSql) {
        String fromHql = orgSql;
        //select??order by???count,?.
        fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
        //      fromHql = StringUtils.substringBefore(fromHql, "order by");

        String countHql = "select count(*) " + fromHql;
        return countHql;
    }

    /*
     * ???
     */
    public <X> X findUniqueBySql(final String sql, final Object... values) {
        return (X) createCountSqlQuery(sql, values).uniqueResult();
    }

    /*
     * ?
     */
    protected Query setPageParameterToSqlQuery(final Query q, final Page<T> page) {

        Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

        //hibernatefirstResult??0
        q.setFirstResult(page.getFirst() - 1);
        q.setMaxResults(page.getPageSize());

        return q;
    }

    public static String camelToUnderline(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append('_');
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
    * ??
    * 
    * @param clazz ?po
    * @return String
    */
    @SuppressWarnings("unchecked")
    protected String getTableName(Class clazz) {
        Table annotation = (Table) clazz.getAnnotation(Table.class);
        if (annotation != null) {
            return annotation.name();
        }

        return null;
    }

    /**
    * ????
        
    *
        
    * @author: zhaozongzhan
        
    * @create: 201618 ?10:43:43
        
    *
        
    * @param showFieldNames entity
    * @param queryFilters ?
    * @return
    */
    public List<T> getAppointedFieldNamesByEntitys(List<String> showFieldNames, List<PropertyFilter> queryFilters) {
        Criterion[] criterions = buildCriterionByPropertyFilter(queryFilters);
        List entitys = findShowFields(showFieldNames, criterions);
        if (entitys != null && entitys.size() > 0) {
            List<T> entitylist = new ArrayList<T>();
            setArrayValuesToEntity(entitys, entitylist, showFieldNames);
            return entitylist;
        } else
            return null;
    }

    /**
    * 
        
    *????
        
    * @author: zhaozongzhan
        
    * @create: 2016114 ?5:57:01
        
    *
        
    * @param showFieldNames
    * @param queryFilters
    * @return
    */
    public T getAppointedFieldNamesByEntity(List<String> showFieldNames, List<PropertyFilter> queryFilters) {
        Criterion[] criterions = buildCriterionByPropertyFilter(queryFilters);
        if (showFieldNames == null || showFieldNames.size() <= 0) {

            return (T) findShowFieldsUniqueResult(showFieldNames, criterions);
        }
        Object o = findShowFieldsUniqueResult(showFieldNames, criterions);

        if (o != null) {
            T entity = null;
            try {
                entity = entityClass.newInstance();

            } catch (Exception e) {
                // TODO Auto-generated catch block
                logger.error("Could not instantiate entityClass: " + entityClass.getName());
                logger.error(String.format("getAppointedFieldNamesByEntity :%s:%",
                        entityClass.getName(), e.getMessage()));
                e.printStackTrace();
                throw new HibernateException("Could not instantiate entityClass: " + entityClass.getName());

            }
            setObjectValuesToEntity(o, entity, showFieldNames);
            return entity;
        } else
            return null;
    }

    /**
     * ???? 
     *VO??
     *VO?? ????? 
                  ?idsetId ?set
                   SQL:SELSECT supplier_id ,SHIPPING_FEE  ,REMIT_SHIPPING_MONEY FROM t_Supplier_Store supplier_id? SupplierStore?supplier_id? Supplier
        
        
     * @author: zhaozongzhan
        
     * @create: 201618 ?6:05:45
        
     *
        
     * @param sql
     * @param vo 
     * VO?? ?????
     * vo??VO ????
     * @param queryParameterValues
     * @return
     */
    public List<T> findBySQL(String sql, Class vo, final Object... queryParameterValues) {

        Query query = createCountSqlQuery(sql, queryParameterValues);
        if (vo == null)
            query.setResultTransformer(new SQLColumnToBean(entityClass));//supplier_idVO??supplierId
        else//vo??VO ????
            query.setResultTransformer(new SQLColumnToBean(vo));//supplier_idVO??supplierId
        List entitys = query.list();
        return entitys;

    }

    /**
     * 
        
     *
        
     * @author: zhaozongzhan
        
     * @create: 2016112 ?5:27:29
        
     *
        
     * @param values ?
     * @param entitylist ?
     * @param showFieldNames  ?
     */

    private void setArrayValuesToEntity(List values, List<T> entitylist, List<String> showFieldNames) {

        if (values != null && values.size() > 0) {

            if (showFieldNames != null && showFieldNames.size() > 0) {
                int showFieldNamesSize = showFieldNames.size();
                List<T> myentitys = new ArrayList();
                for (int i = 0; i < values.size(); i++) {
                    T entity = null;
                    try {
                        entity = entityClass.newInstance();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        logger.error("Could not instantiate entityClass: " + entityClass.getName());
                        logger.error(String.format("getAppointedFieldNamesByEntity :%s:%",
                                entityClass.getName(), e.getMessage()));
                        e.printStackTrace();
                        throw new HibernateException("Could not instantiate entityClass: " + entityClass.getName());

                    }
                    //??HIBERNATE?????
                    if (showFieldNamesSize > 1) {
                        Object[] fieldValueArry = (Object[]) values.get(i);

                        int fieldSize = fieldValueArry.length;

                        for (int f = 0; f < fieldSize; f++) {
                            ClassUtils.setFieldValue(entity, showFieldNames.get(f), fieldValueArry[f]);
                        }

                    } else {
                        Object fieldValueObj = values.get(i);
                        ClassUtils.setFieldValue(entity, showFieldNames.get(0), fieldValueObj);
                    }
                    entitylist.add(entity);
                }

            } else {
                entitylist.addAll(values);
            }

        }

    }

    /**
     * HIBERNATE??
        
     *
        
     * @author: zhaozongzhan
        
     * @create: 2016115 ?10:15:45
        
     *
        
     * @param value HIBERNATE
     * @param entity ?
     * @param showFieldNames ?
     */
    private void setObjectValuesToEntity(Object value, T entity, List<String> showFieldNames) {

        if (value != null && value.equals(entity)) {

            return;
        }

        if (showFieldNames != null && showFieldNames.size() > 0) {

            //??HIBERNATE?????
            if (showFieldNames != null && showFieldNames.size() > 1) {
                Object[] fieldValueArry = (Object[]) value;
                int fieldSize = fieldValueArry.length;

                for (int f = 0; f < fieldSize; f++) {
                    ClassUtils.setFieldValue(entity, showFieldNames.get(f), fieldValueArry[f]);
                }

            } else {

                ClassUtils.setFieldValue(entity, showFieldNames.get(0), value);
            }

        }

    }

    /**
     * 
        
     *Criteria?.
        
     * @author: zhaozongzhan
        
     * @create: 2016113 ?10:46:36
        
     *
        
     * @param page ?
     * @param showFieldNames ?
     * @param criterions ???Criterion.
     * @return  .??.
     */
    public Page<T> pageAppointedFieldNamesByEntity(final Page<T> page, final List<PropertyFilter> filters,
            List<String> showFieldNames) {
        Assert.notNull(page, "page?");
        Criterion[] criterions = buildCriterionByPropertyFilter(filters);
        Criteria c = setShowFields(showFieldNames, criterions);

        if (page.isAutoCount()) {
            long totalCount = countCriteriaResult(c);
            page.setTotalCount(totalCount);
        }

        setPageParameterToCriteria(c, page);

        List result = c.list();
        if (result != null && result.size() > 0) {
            List<T> entitylist = new ArrayList<T>();
            setArrayValuesToEntity(result, entitylist, showFieldNames);
            page.setResult(entitylist);
        }

        return page;
    }

    /**
     * ??
     * @param lsit
     * @return
     * @throws SQLException 
     */
    @Transactional
    public void saveOrupdatBatch(List<Object> list) {

        int batchSize = 100;
        if (list == null || list.isEmpty())
            return;
        Session session = null;
        Transaction tx = null;
        try {
            session = getSessionFactory().openSession();
            tx = session.getTransaction();
            tx.begin();
            for (int i = 0; i < list.size(); i++) {
                session.merge((list.get(i)));
                if (i % batchSize == 0) {
                    session.flush();
                    session.clear();
                }
            }
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            if (null != tx) {
                tx = null;
            }
            if (null != session) {
                session = null;
            }
        }
    }

}