基于hibernate的BaseDAO接口

BaseDao.java

  1. import java.io.Serializable;  
  2. import java.util.Collection;  
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import com.xxx.finance.utils.HibernateHandler;  
  7. import com.xxx.finance.utils.Pagination;  
  8.   
  9. public interface BaseDao<T> {  
  10.   
  11.     /**  
  12.      * 保存实体  
  13.      *   
  14.      * @param entity  
  15.      *            实体对象  
  16.      * @return 实体主键  
  17.      */  
  18.     Object save(Object entity);  
  19.   
  20.     /**  
  21.      *   
  22.      * 删除实体  
  23.      *   
  24.      * @param entity  
  25.      *            实体对象  
  26.      *   
  27.      */  
  28.     void delete(Object entity);  
  29.   
  30.     /**  
  31.      *   
  32.      * 更新实体  
  33.      *   
  34.      * @param entity  
  35.      *            实体对象  
  36.      *   
  37.      */  
  38.     void update(Object entity);  
  39.   
  40.     /**  
  41.      *   
  42.      * 保存或更新实体, 实体没有主键时保存,否则更新  
  43.      *   
  44.      * @param entity  
  45.      *            实体对象  
  46.      *   
  47.      */  
  48.     void saveOrUpdate(Object entity);  
  49.   
  50.     /**  
  51.      *   
  52.      * 批量保存实体  
  53.      *   
  54.      * @param entities  
  55.      *            实体集合  
  56.      */  
  57.     void saveAll(Collection<?> entities);  
  58.   
  59.     /**  
  60.      *   
  61.      * 批量删除实体  
  62.      *   
  63.      * @param entities  
  64.      *            实体集合  
  65.      *   
  66.      */  
  67.     void deleteAll(Collection<?> entities);  
  68.   
  69.     /**  
  70.      *   
  71.      * 批量更新实体  
  72.      *   
  73.      * @param entities  
  74.      *            实体集合  
  75.      *   
  76.      */  
  77.     void updateAll(Collection<?> entity);  
  78.   
  79.     /**  
  80.      *   
  81.      * 批量保存或更新实体, 实体没有主键时保存,否则更新  
  82.      *   
  83.      * @param entity  
  84.      *            实体集合  
  85.      *   
  86.      */  
  87.     void saveOrUpdateAll(Collection<?> entities);  
  88.   
  89.     /**  
  90.      *   
  91.      * 获取单个实体,根据实体类及实体的主键获取。  
  92.      *   
  93.      * @param entityClass  
  94.      *            实体类  
  95.      * @param id  
  96.      *            实体主键  
  97.      * @return 实体对象  
  98.      */  
  99.     @SuppressWarnings("hiding")  
  100.     <T> T get(Class<T> entityClass, Serializable id);  
  101.   
  102.     /**  
  103.      * 获取单个实体,根据查询语句及参数获取。  
  104.      *   
  105.      * @param queryString  
  106.      *            查询语句  
  107.      * @param params  
  108.      *            可选的查询参数  
  109.      * @return 单个实体,如果查询结果有多个,则返回第一个实体  
  110.      */  
  111.     @SuppressWarnings("hiding")  
  112.     <T> T get(CharSequence queryString, Map<String, Object> params);  
  113.   
  114.     /**  
  115.      * 获取单个实体,根据查询语句及参数获取。  
  116.      *   
  117.      * @param queryString  
  118.      *            查询语句  
  119.      * @param params  
  120.      *            可选的查询参数  
  121.      * @return 单个实体,如果查询结果有多个,则返回第一个实体  
  122.      */  
  123.     @SuppressWarnings("hiding")  
  124.     <T> T get(CharSequence queryString, Object... params);  
  125.   
  126.     /**  
  127.      *   
  128.      * 查询实体列表  
  129.      *   
  130.      * @param queryString  
  131.      *            查询语句  
  132.      * @param params  
  133.      *            可选的查询参数  
  134.      * @return 实体列表  
  135.      */  
  136.     @SuppressWarnings("hiding")  
  137.     <T> List<T> findList(CharSequence queryString, Object... params);  
  138.   
  139.     /**  
  140.      *   
  141.      * 查询实体列表  
  142.      *   
  143.      * @param queryString  
  144.      *            查询语句  
  145.      * @param params  
  146.      *            可选的查询参数  
  147.      * @return 实体列表  
  148.      */  
  149.     @SuppressWarnings("hiding")  
  150.     <T> List<T> findList(CharSequence queryString, Map<String, Object> params);  
  151.   
  152.     /**  
  153.      * 分页查询实体  
  154.      *   
  155.      * @param queryString  
  156.      *            查询语句  
  157.      * @param pageIndex  
  158.      *            当前页码,如果pageIndex<1则不分页,且返回pageSize条记录。  
  159.      * @param pageSize  
  160.      *            每页记录数,如果pageSize<1则返回所有记录。  
  161.      * @param params  
  162.      *            可选的查询参数  
  163.      * @return 实体分页对象  
  164.      */  
  165.     @SuppressWarnings("hiding")  
  166.     <T> Pagination<T> findPagination(CharSequence queryString, int pageIndex, int pageSize, Object... params);  
  167.   
  168.     /**  
  169.      * 分页查询实体  
  170.      *   
  171.      * @param queryString  
  172.      *            查询语句  
  173.      * @param params  
  174.      *            可选的查询参数  
  175.      * @param pageIndex  
  176.      *            当前页码,如果pageIndex<2则不分页,且返回pageSize条记录。  
  177.      * @param pageSize  
  178.      *            每页记录数,如果pageSize<1则返回所有记录。  
  179.      *   
  180.      * @return 实体分页对象  
  181.      */  
  182.     @SuppressWarnings("hiding")  
  183.     <T> Pagination<T> findPagination(CharSequence queryString, Map<String, Object> params, int pageIndex, int pageSize);  
  184.   
  185.     /**  
  186.      * 分页查询实体,自定义总条数查询语句,适合复杂的hql分页查询  
  187.      *   
  188.      * @param queryString  
  189.      *            查询语句  
  190.      * @param countString  
  191.      *            查询记录总条数语句  
  192.      * @param pageIndex  
  193.      *            当前页码,如果pageIndex<1则不分页,且返回pageSize条记录。  
  194.      * @param pageSize  
  195.      *            每页记录数,如果pageSize<1则返回所有记录。  
  196.      * @param params  
  197.      *            可选的查询参数  
  198.      * @return 实体分页对象  
  199.      */  
  200.     @SuppressWarnings("hiding")  
  201.     <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString, int pageIndex, int pageSize,  
  202.             Object... params);  
  203.   
  204.     /**  
  205.      * 分页查询实体,自定义总条数查询语句,适合复杂的hql分页查询  
  206.      *   
  207.      * @param queryString  
  208.      *            查询语句  
  209.      * @param countString  
  210.      *            查询记录总条数语句  
  211.      * @param params  
  212.      *            可选的查询参数  
  213.      * @param pageIndex  
  214.      *            当前页码,如果pageIndex<2则不分页,且返回pageSize条记录。  
  215.      * @param pageSize  
  216.      *            每页记录数,如果pageSize<1则返回所有记录。  
  217.      *   
  218.      * @return 实体分页对象  
  219.      */  
  220.     @SuppressWarnings("hiding")  
  221.     <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString, Map<String, Object> params,  
  222.             int pageIndex, int pageSize);  
  223.   
  224.     /**  
  225.      * 分页查询实体,自定义总条数查询语句,适合复杂的sql分页查询  
  226.      *   
  227.      * @param queryString  
  228.      *            查询语句  
  229.      * @param countString  
  230.      *            查询记录总条数语句  
  231.      * @param params  
  232.      *            可选的查询参数  
  233.      * @param pageIndex  
  234.      *            当前页码,如果pageIndex<2则不分页,且返回pageSize条记录。  
  235.      * @param pageSize  
  236.      *            每页记录数,如果pageSize<1则返回所有记录。  
  237.      *   
  238.      * @return 实体分页对象  
  239.      */  
  240.     @SuppressWarnings("hiding")  
  241.     public <T> Pagination<T> findSqlPagination(final CharSequence queryString, final CharSequence countString,  
  242.             final Map<String, Object> params, int pageIndex, int pageSize);  
  243.   
  244.     /**  
  245.      * 执行数据库更新操作  
  246.      *   
  247.      * @deprecated 用{@link #executeUpdate(String)}替换  
  248.      * @param hql  
  249.      */  
  250.     void execute(String hql);  
  251.   
  252.     /**  
  253.      * 执行数据库更新操作  
  254.      *   
  255.      * @deprecated 用{@link #executeUpdate(HibernateHandler)}替换  
  256.      * @param hql  
  257.      */  
  258.     void execute(HibernateHandler handler);  
  259.   
  260.     /**  
  261.      * 执行数据库更新操作  
  262.      *   
  263.      * @deprecated 用{@link #executeSqlUpdate(String)}替换  
  264.      * @param sql  
  265.      */  
  266.     void executeSql(String sql);  
  267.   
  268.     /**  
  269.      * 执行数据库查询操作  
  270.      *   
  271.      * @param handler  
  272.      *            处理器  
  273.      * @return  
  274.      * @throws Exception  
  275.      */  
  276.     Object executeQuery(HibernateHandler handler);  
  277.   
  278.     /**  
  279.      * 执行数据库更新操作  
  280.      *   
  281.      * @param sql  
  282.      * @return 更新的记录条数  
  283.      */  
  284.     int executeSqlUpdate(String sql);  
  285.   
  286.     /**  
  287.      * 执行数据库更新操作  
  288.      *   
  289.      * @param hql  
  290.      * @return 更新的记录条数  
  291.      */  
  292.     int executeUpdate(String hql);  
  293.   
  294.     /**  
  295.      * 执行数据库更新操作  
  296.      *   
  297.      * @param handler  
  298.      *            处理器  
  299.      * @return  
  300.      * @throws Exception  
  301.      */  
  302.     Object executeUpdate(HibernateHandler handler);  
  303.   
  304.     public T getById(Serializable id);  
  305.   
  306.     public T saveEntity(T o);  
  307.   
  308.     public T insert(T o);  
  309.   
  310.     public void save(List<T> list);  
  311.   
  312.     public void insert(List<T> list);  
  313.   
  314.     public void delete(List<T> list);  
  315.   
  316.     public void update(List<T> list);  
  317.   
  318.     public List<T> findByProperty(String name, Object value);  
  319.   
  320.     public List<T> findByProperty(Map<String, Object> conditionMap);  
  321.   
  322.     /**  
  323.      *   
  324.      * 查询实体列表  
  325.      *   
  326.      * @param queryString  
  327.      *            查询语句  
  328.      * @param maxResults  
  329.      *            列表最大数  
  330.      * @param params  
  331.      *            可选的查询参数  
  332.      * @return 实体列表  
  333.      */  
  334.     public <V> List<V> findListByMax(CharSequence queryString, int maxResults, Object... params);  
  335.   
  336.     /**  
  337.      *   
  338.      * 查询实体列表  
  339.      *   
  340.      * @param queryString  
  341.      *            查询语句  
  342.      * @param maxResults  
  343.      *            列表最大数  
  344.      * @param params  
  345.      *            可选的查询参数  
  346.      * @return 实体列表  
  347.      */  
  348.     public <V> List<V> findListByMax(CharSequence queryString, int maxResults, Map<String, Object> params);  
  349. }  
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.xxx.finance.utils.HibernateHandler;
import com.xxx.finance.utils.Pagination;

public interface BaseDao<T> {

    /**
     * 保存实体
     * 
     * @param entity
     *            实体对象
     * @return 实体主键
     */
    Object save(Object entity);

    /**
     * 
     * 删除实体
     * 
     * @param entity
     *            实体对象
     * 
     */
    void delete(Object entity);

    /**
     * 
     * 更新实体
     * 
     * @param entity
     *            实体对象
     * 
     */
    void update(Object entity);

    /**
     * 
     * 保存或更新实体, 实体没有主键时保存,否则更新
     * 
     * @param entity
     *            实体对象
     * 
     */
    void saveOrUpdate(Object entity);

    /**
     * 
     * 批量保存实体
     * 
     * @param entities
     *            实体集合
     */
    void saveAll(Collection<?> entities);

    /**
     * 
     * 批量删除实体
     * 
     * @param entities
     *            实体集合
     * 
     */
    void deleteAll(Collection<?> entities);

    /**
     * 
     * 批量更新实体
     * 
     * @param entities
     *            实体集合
     * 
     */
    void updateAll(Collection<?> entity);

    /**
     * 
     * 批量保存或更新实体, 实体没有主键时保存,否则更新
     * 
     * @param entity
     *            实体集合
     * 
     */
    void saveOrUpdateAll(Collection<?> entities);

    /**
     * 
     * 获取单个实体,根据实体类及实体的主键获取。
     * 
     * @param entityClass
     *            实体类
     * @param id
     *            实体主键
     * @return 实体对象
     */
    @SuppressWarnings("hiding")
    <T> T get(Class<T> entityClass, Serializable id);

    /**
     * 获取单个实体,根据查询语句及参数获取。
     * 
     * @param queryString
     *            查询语句
     * @param params
     *            可选的查询参数
     * @return 单个实体,如果查询结果有多个,则返回第一个实体
     */
    @SuppressWarnings("hiding")
    <T> T get(CharSequence queryString, Map<String, Object> params);

    /**
     * 获取单个实体,根据查询语句及参数获取。
     * 
     * @param queryString
     *            查询语句
     * @param params
     *            可选的查询参数
     * @return 单个实体,如果查询结果有多个,则返回第一个实体
     */
    @SuppressWarnings("hiding")
    <T> T get(CharSequence queryString, Object... params);

    /**
     * 
     * 查询实体列表
     * 
     * @param queryString
     *            查询语句
     * @param params
     *            可选的查询参数
     * @return 实体列表
     */
    @SuppressWarnings("hiding")
    <T> List<T> findList(CharSequence queryString, Object... params);

    /**
     * 
     * 查询实体列表
     * 
     * @param queryString
     *            查询语句
     * @param params
     *            可选的查询参数
     * @return 实体列表
     */
    @SuppressWarnings("hiding")
    <T> List<T> findList(CharSequence queryString, Map<String, Object> params);

    /**
     * 分页查询实体
     * 
     * @param queryString
     *            查询语句
     * @param pageIndex
     *            当前页码,如果pageIndex<1则不分页,且返回pageSize条记录。
     * @param pageSize
     *            每页记录数,如果pageSize<1则返回所有记录。
     * @param params
     *            可选的查询参数
     * @return 实体分页对象
     */
    @SuppressWarnings("hiding")
    <T> Pagination<T> findPagination(CharSequence queryString, int pageIndex, int pageSize, Object... params);

    /**
     * 分页查询实体
     * 
     * @param queryString
     *            查询语句
     * @param params
     *            可选的查询参数
     * @param pageIndex
     *            当前页码,如果pageIndex<2则不分页,且返回pageSize条记录。
     * @param pageSize
     *            每页记录数,如果pageSize<1则返回所有记录。
     * 
     * @return 实体分页对象
     */
    @SuppressWarnings("hiding")
    <T> Pagination<T> findPagination(CharSequence queryString, Map<String, Object> params, int pageIndex, int pageSize);

    /**
     * 分页查询实体,自定义总条数查询语句,适合复杂的hql分页查询
     * 
     * @param queryString
     *            查询语句
     * @param countString
     *            查询记录总条数语句
     * @param pageIndex
     *            当前页码,如果pageIndex<1则不分页,且返回pageSize条记录。
     * @param pageSize
     *            每页记录数,如果pageSize<1则返回所有记录。
     * @param params
     *            可选的查询参数
     * @return 实体分页对象
     */
    @SuppressWarnings("hiding")
    <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString, int pageIndex, int pageSize,
            Object... params);

    /**
     * 分页查询实体,自定义总条数查询语句,适合复杂的hql分页查询
     * 
     * @param queryString
     *            查询语句
     * @param countString
     *            查询记录总条数语句
     * @param params
     *            可选的查询参数
     * @param pageIndex
     *            当前页码,如果pageIndex<2则不分页,且返回pageSize条记录。
     * @param pageSize
     *            每页记录数,如果pageSize<1则返回所有记录。
     * 
     * @return 实体分页对象
     */
    @SuppressWarnings("hiding")
    <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString, Map<String, Object> params,
            int pageIndex, int pageSize);

    /**
     * 分页查询实体,自定义总条数查询语句,适合复杂的sql分页查询
     * 
     * @param queryString
     *            查询语句
     * @param countString
     *            查询记录总条数语句
     * @param params
     *            可选的查询参数
     * @param pageIndex
     *            当前页码,如果pageIndex<2则不分页,且返回pageSize条记录。
     * @param pageSize
     *            每页记录数,如果pageSize<1则返回所有记录。
     * 
     * @return 实体分页对象
     */
    @SuppressWarnings("hiding")
    public <T> Pagination<T> findSqlPagination(final CharSequence queryString, final CharSequence countString,
            final Map<String, Object> params, int pageIndex, int pageSize);

    /**
     * 执行数据库更新操作
     * 
     * @deprecated 用{@link #executeUpdate(String)}替换
     * @param hql
     */
    void execute(String hql);

    /**
     * 执行数据库更新操作
     * 
     * @deprecated 用{@link #executeUpdate(HibernateHandler)}替换
     * @param hql
     */
    void execute(HibernateHandler handler);

    /**
     * 执行数据库更新操作
     * 
     * @deprecated 用{@link #executeSqlUpdate(String)}替换
     * @param sql
     */
    void executeSql(String sql);

    /**
     * 执行数据库查询操作
     * 
     * @param handler
     *            处理器
     * @return
     * @throws Exception
     */
    Object executeQuery(HibernateHandler handler);

    /**
     * 执行数据库更新操作
     * 
     * @param sql
     * @return 更新的记录条数
     */
    int executeSqlUpdate(String sql);

    /**
     * 执行数据库更新操作
     * 
     * @param hql
     * @return 更新的记录条数
     */
    int executeUpdate(String hql);

    /**
     * 执行数据库更新操作
     * 
     * @param handler
     *            处理器
     * @return
     * @throws Exception
     */
    Object executeUpdate(HibernateHandler handler);

    public T getById(Serializable id);

    public T saveEntity(T o);

    public T insert(T o);

    public void save(List<T> list);

    public void insert(List<T> list);

    public void delete(List<T> list);

    public void update(List<T> list);

    public List<T> findByProperty(String name, Object value);

    public List<T> findByProperty(Map<String, Object> conditionMap);

    /**
     * 
     * 查询实体列表
     * 
     * @param queryString
     *            查询语句
     * @param maxResults
     *            列表最大数
     * @param params
     *            可选的查询参数
     * @return 实体列表
     */
    public <V> List<V> findListByMax(CharSequence queryString, int maxResults, Object... params);

    /**
     * 
     * 查询实体列表
     * 
     * @param queryString
     *            查询语句
     * @param maxResults
     *            列表最大数
     * @param params
     *            可选的查询参数
     * @return 实体列表
     */
    public <V> List<V> findListByMax(CharSequence queryString, int maxResults, Map<String, Object> params);
}

BaseDaoImpl.java

  1. import java.io.Serializable;  
  2. import java.lang.reflect.ParameterizedType;  
  3. import java.lang.reflect.Type;  
  4. import java.math.BigInteger;  
  5. import java.text.ParseException;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.ArrayList;  
  8. import java.util.Calendar;  
  9. import java.util.Collection;  
  10. import java.util.Date;  
  11. import java.util.Iterator;  
  12. import java.util.List;  
  13. import java.util.Map;  
  14.   
  15. import javax.annotation.Resource;  
  16.   
  17. import org.hibernate.Query;  
  18. import org.hibernate.SQLQuery;  
  19. import org.hibernate.Session;  
  20. import org.hibernate.SessionFactory;  
  21. import org.hibernate.transform.Transformers;  
  22. import org.springframework.stereotype.Repository;  
  23.   
  24. import com.xxx.finance.dao.BaseDao;  
  25. import com.xxx.finance.utils.HibernateHandler;  
  26. import com.xxx.finance.utils.ObjectUtil;  
  27. import com.xxx.finance.utils.Pagination;  
  28.   
  29. /**  
  30.  * @author   
  31.  */  
  32. @Repository  
  33. public class BaseDaoImpl<T> implements BaseDao<T> {  
  34.   
  35.     protected Class<T> entityClazz;  
  36.   
  37.     protected SessionFactory sessionFactory;  
  38.   
  39.     @SuppressWarnings("unchecked")  
  40.     public BaseDaoImpl() {  
  41.         Type type = getClass().getGenericSuperclass();  
  42.         if (type instanceof ParameterizedType) {  
  43.             this.entityClazz = (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0];  
  44.         } else {  
  45.             this.entityClazz = null;  
  46.         }  
  47.     }  
  48.   
  49.     @Resource  
  50.     public void setSessionFactory(SessionFactory sessionFactory) {  
  51.         this.sessionFactory = sessionFactory;  
  52.     }  
  53.   
  54.     protected Session getSession() {  
  55.         return sessionFactory.getCurrentSession();  
  56.     }  
  57.   
  58.     @SuppressWarnings("unchecked")  
  59.     public Object save(Object entity) {  
  60.         return (T) getSession().save(entity);  
  61.     }  
  62.   
  63.     public void delete(Object entity) {  
  64.   
  65.         getSession().delete(entity);  
  66.     }  
  67.   
  68.     public void update(Object entity) {  
  69.   
  70.         getSession().update(entity);  
  71.     }  
  72.   
  73.     public void saveOrUpdate(Object entity) {  
  74.   
  75.         getSession().saveOrUpdate(entity);  
  76.     }  
  77.   
  78.     public void saveAll(Collection<?> entities) {  
  79.   
  80.         for (@SuppressWarnings("rawtypes")  
  81.         Iterator localIterator = entities.iterator(); localIterator.hasNext();) {  
  82.             Object entity = localIterator.next();  
  83.             getSession().save(entity);  
  84.         }  
  85.     }  
  86.   
  87.     public void deleteAll(Collection<?> entities) {  
  88.   
  89.         for (@SuppressWarnings("rawtypes")  
  90.         Iterator localIterator = entities.iterator(); localIterator.hasNext();) {  
  91.             Object entity = localIterator.next();  
  92.             getSession().delete(entity);  
  93.         }  
  94.     }  
  95.   
  96.     public void updateAll(Collection<?> entities) {  
  97.   
  98.         for (@SuppressWarnings("rawtypes")  
  99.         Iterator localIterator = entities.iterator(); localIterator.hasNext();) {  
  100.             Object entity = localIterator.next();  
  101.             getSession().update(entity);  
  102.         }  
  103.     }  
  104.   
  105.     public void saveOrUpdateAll(Collection<?> entities) {  
  106.   
  107.         for (@SuppressWarnings("rawtypes")  
  108.         Iterator localIterator = entities.iterator(); localIterator.hasNext();) {  
  109.             Object entity = localIterator.next();  
  110.             getSession().saveOrUpdate(entity);  
  111.         }  
  112.     }  
  113.   
  114.     @SuppressWarnings({ "unchecked", "hiding" })  
  115.     public <T> T get(Class<T> entityClass, Serializable id) {  
  116.   
  117.         return (T) getSession().get(entityClass, id);  
  118.     }  
  119.   
  120.     @SuppressWarnings({ "unchecked", "rawtypes", "hiding" })  
  121.     public <T> T get(CharSequence queryString, Object... params) {  
  122.   
  123.         Query qry = getSession().createQuery(queryString.toString());  
  124.         for (int i = 0; i < params.length; ++i) {  
  125.             qry.setParameter(i, params[i]);  
  126.         }  
  127.         List list = qry.setMaxResults(1).list();  
  128.         if (list.isEmpty())  
  129.             return null;  
  130.         return (T) list.get(0);  
  131.     }  
  132.   
  133.     @SuppressWarnings({ "unchecked", "hiding" })  
  134.     public <T> T get(CharSequence queryString, Map<String, Object> params) {  
  135.   
  136.         Query qry = getSession().createQuery(queryString.toString());  
  137.         setParameter(qry, params);  
  138.         @SuppressWarnings("rawtypes")  
  139.         List list = qry.setMaxResults(1).list();  
  140.         if (list.isEmpty())  
  141.             return null;  
  142.         return (T) list.get(0);  
  143.     }  
  144.   
  145.     @SuppressWarnings({ "unchecked", "hiding" })  
  146.     public <T> List<T> findList(CharSequence queryString, Object... params) {  
  147.         Query query = getSession().createQuery(queryString.toString());  
  148.         for (int i = 0; i < params.length; ++i) {  
  149.             query.setParameter(i, params[i]);  
  150.         }  
  151.         return query.list();  
  152.     }  
  153.   
  154.     @SuppressWarnings({ "unchecked", "hiding" })  
  155.     public <T> List<T> findList(CharSequence queryString, Map<String, Object> params) {  
  156.         Query query = getSession().createQuery(queryString.toString());  
  157.         setParameter(query, params);  
  158.         return query.list();  
  159.     }  
  160.   
  161.     @SuppressWarnings({ "unchecked", "hiding" })  
  162.     public <T> Pagination<T> findPagination(CharSequence queryString, int pageIndex, int pageSize, Object... params) {  
  163.         Query query = getSession().createQuery(queryString.toString());  
  164.   
  165.         if ((pageSize > 0) && (pageIndex > 0)) {  
  166.             query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);  
  167.             query.setMaxResults(pageSize);  
  168.         }  
  169.   
  170.         for (int i = 0; i < params.length; ++i) {  
  171.             query.setParameter(i, params[i]);  
  172.         }  
  173.         @SuppressWarnings("rawtypes")  
  174.         List items = query.list();  
  175.         long rowsCount = 0L;  
  176.   
  177.         if ((pageSize > 0) && (pageIndex > 0)) {  
  178.             String hql = parseSelectCount(queryString.toString());  
  179.             rowsCount = ((Long) get(hql, params)).longValue();  
  180.         } else {  
  181.             rowsCount = items.size();  
  182.         }  
  183.   
  184.         @SuppressWarnings("rawtypes")  
  185.         Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);  
  186.         pagination.setItems(items);  
  187.         return pagination;  
  188.     }  
  189.   
  190.     @SuppressWarnings({ "unchecked", "hiding" })  
  191.     public <T> Pagination<T> findPagination(CharSequence queryString, Map<String, Object> params, int pageIndex,  
  192.             int pageSize) {  
  193.         Query query = getSession().createQuery(queryString.toString());  
  194.   
  195.         if ((pageSize > 0) && (pageIndex > 0)) {  
  196.             query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);  
  197.             query.setMaxResults(pageSize);  
  198.         }  
  199.   
  200.         setParameter(query, params);  
  201.         @SuppressWarnings({ "rawtypes" })  
  202.         List items = query.list();  
  203.         long rowsCount = 0L;  
  204.   
  205.         if ((pageSize > 0) && (pageIndex > 0)) {  
  206.             String hql = parseSelectCount(queryString.toString());  
  207.             rowsCount = ((Long) get(hql, params)).longValue();  
  208.         } else {  
  209.             rowsCount = items.size();  
  210.         }  
  211.   
  212.         @SuppressWarnings("rawtypes")  
  213.         Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);  
  214.         pagination.setItems(items);  
  215.         return pagination;  
  216.     }  
  217.   
  218.     @SuppressWarnings({ "unchecked", "hiding" })  
  219.     public <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString, int pageIndex,  
  220.             int pageSize, Object... params) {  
  221.         Query query = getSession().createQuery(queryString.toString());  
  222.   
  223.         if ((pageSize > 0) && (pageIndex > 0)) {  
  224.             query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);  
  225.             query.setMaxResults(pageSize);  
  226.         }  
  227.   
  228.         for (int i = 0; i < params.length; ++i) {  
  229.             query.setParameter(i, params[i]);  
  230.         }  
  231.         @SuppressWarnings("rawtypes")  
  232.         List items = query.list();  
  233.         long rowsCount = 0L;  
  234.   
  235.         if ((pageSize > 0) && (pageIndex > 0)) {  
  236.             rowsCount = ((Long) get(countString, params)).longValue();  
  237.         } else  
  238.             rowsCount = items.size();  
  239.   
  240.         @SuppressWarnings("rawtypes")  
  241.         Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);  
  242.         pagination.setItems(items);  
  243.         return pagination;  
  244.     }  
  245.   
  246.     @SuppressWarnings({ "unchecked", "hiding" })  
  247.     public <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString,  
  248.             Map<String, Object> params, int pageIndex, int pageSize) {  
  249.         Query query = getSession().createQuery(queryString.toString());  
  250.   
  251.         if ((pageSize > 0) && (pageIndex > 0)) {  
  252.             query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);  
  253.             query.setMaxResults(pageSize);  
  254.         }  
  255.   
  256.         setParameter(query, params);  
  257.         @SuppressWarnings("rawtypes")  
  258.         List items = query.list();  
  259.         long rowsCount = 0L;  
  260.   
  261.         if ((pageSize > 0) && (pageIndex > 0)) {  
  262.             rowsCount = ((Long) get(countString, params)).longValue();  
  263.         } else  
  264.             rowsCount = items.size();  
  265.   
  266.         @SuppressWarnings("rawtypes")  
  267.         Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);  
  268.         pagination.setItems(items);  
  269.         return pagination;  
  270.     }  
  271.   
  272.     @SuppressWarnings({ "serial", "unchecked", "hiding" })  
  273.     public <T> Pagination<T> findSqlPagination(CharSequence queryString, final CharSequence countString,  
  274.             final Map<String, Object> params, int pageIndex, int pageSize) {  
  275.         SQLQuery query = getSession().createSQLQuery(queryString.toString());  
  276.         query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);  
  277.   
  278.         if ((pageSize > 0) && (pageIndex > 0)) {  
  279.             query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);  
  280.             query.setMaxResults(pageSize);  
  281.         }  
  282.         if ((params != null) && (!(params.isEmpty()))) {  
  283.             setParameter(query, params);  
  284.         }  
  285.         @SuppressWarnings("rawtypes")  
  286.         List items = query.list();  
  287.         BigInteger rowsCount = BigInteger.valueOf(0L);  
  288.   
  289.         if ((pageSize > 0) && (pageIndex > 0)) {  
  290.             rowsCount = (BigInteger) executeQuery(new HibernateHandler() {  
  291.                 public Object doInHibernate(Session session) {  
  292.                     SQLQuery query = session.createSQLQuery(countString.toString());  
  293.                     if ((params != null) && (!(params.isEmpty()))) {  
  294.                         setParameter(query, params);  
  295.                     }  
  296.                     return query.uniqueResult();  
  297.                 }  
  298.             });  
  299.         }  
  300.   
  301.         @SuppressWarnings("rawtypes")  
  302.         Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount.intValue());  
  303.         pagination.setItems(items);  
  304.         return pagination;  
  305.     }  
  306.   
  307.     public Object executeQuery(HibernateHandler handler) {  
  308.         return handler.doInHibernate(getSession());  
  309.     }  
  310.   
  311.     public void execute(String hql) {  
  312.         executeUpdate(hql);  
  313.     }  
  314.   
  315.     public void execute(HibernateHandler handler) {  
  316.         executeUpdate(handler);  
  317.     }  
  318.   
  319.     public void executeSql(String sql) {  
  320.         executeSqlUpdate(sql);  
  321.     }  
  322.   
  323.     public int executeSqlUpdate(String sql) {  
  324.         return getSession().createSQLQuery(sql).executeUpdate();  
  325.     }  
  326.   
  327.     public int executeUpdate(String hql) {  
  328.         return getSession().createQuery(hql).executeUpdate();  
  329.     }  
  330.   
  331.     public Object executeUpdate(HibernateHandler handler) {  
  332.         return handler.doInHibernate(getSession());  
  333.     }  
  334.   
  335.     protected Query setParameter(Query query, Map<String, Object> parameterMap) {  
  336.         for (@SuppressWarnings("rawtypes")  
  337.         Iterator iterator = parameterMap.keySet().iterator(); iterator.hasNext();) {  
  338.             String key = (String) iterator.next();  
  339.             query.setParameter(key, parameterMap.get(key));  
  340.         }  
  341.         return query;  
  342.     }  
  343.   
  344.     protected boolean followWithWord(String s, String sub, int pos) {  
  345.         int i = 0;  
  346.         for (; (pos < s.length()) && (i < sub.length()); ++i) {  
  347.             if (s.charAt(pos) != sub.charAt(i))  
  348.                 return false;  
  349.             ++pos;  
  350.         }  
  351.   
  352.         if (i < sub.length()) {  
  353.             return false;  
  354.         }  
  355.   
  356.         if (pos >= s.length()) {  
  357.             return true;  
  358.         }  
  359.         return (!(isAlpha(s.charAt(pos))));  
  360.     }  
  361.   
  362.     protected String parseSelectCount(String queryString) {  
  363.         String hql = queryString.toLowerCase();  
  364.         int noBlankStart = 0;  
  365.         for (int len = hql.length(); noBlankStart < len; ++noBlankStart) {  
  366.             if (hql.charAt(noBlankStart) > ' ') {  
  367.                 break;  
  368.             }  
  369.         }  
  370.   
  371.         int pair = 0;  
  372.   
  373.         if (!(followWithWord(hql, "select", noBlankStart))) {  
  374.             pair = 1;  
  375.         }  
  376.         int fromPos = -1;  
  377.         for (int i = noBlankStart; i < hql.length();) {  
  378.             if (followWithWord(hql, "select", i)) {  
  379.                 ++pair;  
  380.                 i += "select".length();  
  381.             } else if (followWithWord(hql, "from", i)) {  
  382.                 --pair;  
  383.                 if (pair == 0) {  
  384.                     fromPos = i;  
  385.                     break;  
  386.                 }  
  387.                 i += "from".length();  
  388.             } else {  
  389.                 ++i;  
  390.             }  
  391.         }  
  392.         if (fromPos == -1) {  
  393.             throw new IllegalArgumentException("parse count sql error, check your sql/hql");  
  394.         }  
  395.   
  396.         String countHql = "select count(*) " + queryString.substring(fromPos);  
  397.         return countHql;  
  398.     }  
  399.   
  400.     protected boolean isAlpha(char c) {  
  401.         return ((c == '_') || (('0' <= c) && (c <= '9')) || (('a' <= c) && (c <= 'z')) || (('A' <= c) && (c <= 'Z')));  
  402.     }  
  403.   
  404.     public void delete(Serializable id) {  
  405.         T entity = getById(id);  
  406.         delete(entity);  
  407.     }  
  408.   
  409.     public void delete(List<T> entitys) {  
  410.         for (T entity : entitys) {  
  411.             delete(entity);  
  412.         }  
  413.     }  
  414.   
  415.     public T getById(Serializable id) {  
  416.         if (id == null)  
  417.             return null;  
  418.   
  419.         return (T) get(entityClazz, id);  
  420.     }  
  421.   
  422.     @Override  
  423.     public T saveEntity(T o) {  
  424.         saveOrUpdate(o);  
  425.         return o;  
  426.     }  
  427.   
  428.     @Override  
  429.     public void save(List<T> list) {  
  430.         saveOrUpdateAll(list);  
  431.     }  
  432.   
  433.     @Override  
  434.     public T insert(T entity) {  
  435.         save(entity);  
  436.         return entity;  
  437.     }  
  438.   
  439.     @Override  
  440.     public void insert(List<T> entitys) {  
  441.         for (T entity : entitys) {  
  442.             save(entity);  
  443.         }  
  444.     }  
  445.   
  446.     @Override  
  447.     public void update(List<T> entitys) {  
  448.         for (T entity : entitys) {  
  449.             update(entity);  
  450.         }  
  451.     }  
  452.   
  453.     @Override  
  454.     public List<T> findByProperty(String name, Object value) {  
  455.         String hql = "from  " + entityClazz.getSimpleName() + " where " + name + "=? ";  
  456.         return findList(hql, value);  
  457.     }  
  458.   
  459.     @Override  
  460.     public List<T> findByProperty(Map<String, Object> conditionMap) {  
  461.         StringBuilder hql = new StringBuilder();  
  462.         hql.append("from  " + entityClazz.getSimpleName());  
  463.         if (!conditionMap.isEmpty()) {  
  464.             Iterator<String> it = conditionMap.keySet().iterator();  
  465.             String key = it.next();  
  466.             hql.append(" where  " + key + "=:" + key);  
  467.             while (it.hasNext()) {  
  468.                 key = it.next();  
  469.                 hql.append(" and  " + key + "=:" + key);  
  470.             }  
  471.         }  
  472.         return findList(hql.toString(), conditionMap);  
  473.     }  
  474.   
  475.     @Override  
  476.     public <V> List<V> findListByMax(final CharSequence queryString, final int maxResults, final Object... params) {  
  477.         @SuppressWarnings({ "unchecked", "serial" })  
  478.         List<V> list = (List<V>) executeQuery(new HibernateHandler() {  
  479.             @Override  
  480.             public List<V> doInHibernate(Session paramSession) {  
  481.                 try {  
  482.                     Query query = paramSession.createQuery(queryString.toString());  
  483.                     for (int i = 0; i < params.length; ++i) {  
  484.                         query.setParameter(i, params[i]);  
  485.                     }  
  486.                     return query.setMaxResults(maxResults).list();  
  487.                 } catch (RuntimeException re) {  
  488.                     throw re;  
  489.                 }  
  490.             }  
  491.         });  
  492.         return list;  
  493.     }  
  494.   
  495.     @Override  
  496.     public <V> List<V> findListByMax(final CharSequence queryString, final int maxResults,  
  497.             final Map<String, Object> params) {  
  498.         @SuppressWarnings({ "unchecked", "serial" })  
  499.         List<V> list = (List<V>) executeQuery(new HibernateHandler() {  
  500.             @Override  
  501.             public List<V> doInHibernate(Session paramSession) {  
  502.                 try {  
  503.                     Query query = paramSession.createQuery(queryString.toString());  
  504.                     for (Iterator<String> iterator = params.keySet().iterator(); iterator.hasNext();) {  
  505.                         String key = iterator.next();  
  506.                         query.setParameter(key, params.get(key));  
  507.                     }  
  508.                     return query.setMaxResults(maxResults).list();  
  509.                 } catch (RuntimeException re) {  
  510.                     throw re;  
  511.                 }  
  512.             }  
  513.   
  514.         });  
  515.         return list;  
  516.     }  
  517.   
  518.     /**  
  519.      * HQL/SQL之数据操作命令(DML)拼接辅助类  
  520.      *   
  521.      * @author PanJun  
  522.      * @deprecated by fu.zhanghua  
  523.      *   
  524.      */  
  525.     public class DmlHelper {  
  526.   
  527.         private ThreadLocal<Calendar> cal = new ThreadLocal<Calendar>() {  
  528.             @Override  
  529.             protected Calendar initialValue() {  
  530.                 return Calendar.getInstance();  
  531.             }  
  532.         };  
  533.   
  534.         /** HQL/SQL参数 */  
  535.         public final List<Object> paramList = new ArrayList<Object>();  
  536.         /** HQL/SQL语句 */  
  537.         public final StringBuilder dmlCmd = new StringBuilder();  
  538.   
  539.         public DmlHelper() {  
  540.         }  
  541.   
  542.         public DmlHelper(CharSequence dml, Object... params) {  
  543.             if (dml != null) {  
  544.                 dmlCmd.append(dml);  
  545.                 for (Object o : params) {  
  546.                     paramList.add(o);  
  547.                 }  
  548.             }  
  549.         }  
  550.   
  551.         @Override  
  552.         public String toString() {  
  553.             return "dml=" + dmlCmd + "params=" + paramList;  
  554.         }  
  555.   
  556.         public DmlHelper append(CharSequence dmlPart, Object... params) {  
  557.             if (dmlPart != null) {  
  558.                 dmlCmd.append(" ").append(dmlPart);  
  559.                 for (Object o : params) {  
  560.                     paramList.add(o);  
  561.                 }  
  562.             }  
  563.             return this;  
  564.         }  
  565.   
  566.         public DmlHelper addEqual(String fieldName, Object value, Object... nullVal) {  
  567.             if (value == null || fieldName == null) {  
  568.                 return this;  
  569.             }  
  570.   
  571.             if (value instanceof String) {  
  572.                 value = value.toString().trim();  
  573.                 if ("".equals(value)) {  
  574.                     return this;  
  575.                 }  
  576.             }  
  577.   
  578.             for (Object NULL : nullVal) {  
  579.                 if (NULL == value) {  
  580.                     return this;  
  581.                 }  
  582.   
  583.                 if (value.equals(NULL)) {  
  584.                     return this;  
  585.                 }  
  586.             }  
  587.   
  588.             dmlCmd.append(" and ").append(fieldName).append("=? ");  
  589.             paramList.add(value);  
  590.             return this;  
  591.         }  
  592.   
  593.         public DmlHelper addLikeAll(String name, String value) {  
  594.             if (null == value || null == name)  
  595.                 return this;  
  596.   
  597.             value = "%" + value.trim().toLowerCase() + "%";  
  598.             dmlCmd.append(" and lower(").append(name).append(") like ? ");  
  599.             paramList.add(value);  
  600.             return this;  
  601.         }  
  602.   
  603.         /**  
  604.          * 清除时间里的时分秒,只留日期  
  605.          *   
  606.          * @param date  
  607.          * @return new date  
  608.          */  
  609.         private void clearTime(Calendar calendar) {  
  610.             int y = calendar.get(Calendar.YEAR);  
  611.             int m = calendar.get(Calendar.MONTH);  
  612.             int d = calendar.get(Calendar.DAY_OF_MONTH);  
  613.             calendar.clear();  
  614.             calendar.set(Calendar.YEAR, y);  
  615.             calendar.set(Calendar.MONTH, m);  
  616.             calendar.set(Calendar.DAY_OF_MONTH, d);  
  617.         }  
  618.   
  619.         /**  
  620.          * 添加开始日期、结束日期(注意时分秒不记入查询条件)查询条件,包含开始日期和结束日期  
  621.          *   
  622.          * @param fieldName  
  623.          *            hbm对象属性名称或字段名  
  624.          * @param minDay  
  625.          *            开始日期  
  626.          * @param maxDay  
  627.          *            结果日期  
  628.          */  
  629.         public DmlHelper addDayRange(String fieldName, Date minDay, Date maxDay) {  
  630.             Calendar calendar = cal.get();  
  631.             if (minDay != null) {  
  632.                 calendar.setTime(minDay);  
  633.                 clearTime(calendar);  
  634.                 calendar.add(Calendar.SECOND, -1);  
  635.                 dmlCmd.append(" and ").append(fieldName).append(">? ");  
  636.                 paramList.add(calendar.getTime());  
  637.             }  
  638.   
  639.             if (maxDay != null) {  
  640.                 calendar.setTime(maxDay);  
  641.                 clearTime(calendar);  
  642.                 calendar.add(Calendar.DAY_OF_MONTH, 1);  
  643.                 dmlCmd.append(" and ").append(fieldName).append("<? ");  
  644.                 paramList.add(calendar.getTime());  
  645.             }  
  646.             return this;  
  647.         }  
  648.   
  649.         /**  
  650.          * 添加开始时间、结束时间查询条件,包含开始时间和结束时间  
  651.          *   
  652.          * @param fieldName  
  653.          *            hbm对象属性名称或字段名  
  654.          * @param minTime  
  655.          *            开始时间  
  656.          * @param maxTime  
  657.          *            结果时间  
  658.          */  
  659.         public DmlHelper addDayRange(String fieldName, String minTime, String maxTime) {  
  660.             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
  661.             Date start_ = nullend_ = null;  
  662.             if (ObjectUtil.hasText(minTime) && ObjectUtil.hasText(maxTime)) {  
  663.                 try {  
  664.                     start_ = sdf.parse(minTime);  
  665.                     end_ = sdf.parse(maxTime);  
  666.                 } catch (ParseException e) {  
  667.                 }  
  668.             }  
  669.   
  670.             return addTimeRange(fieldName, start_, end_);  
  671.         }  
  672.   
  673.         /**  
  674.          * 添加开始时间、结束时间查询条件,包含开始时间和结束时间  
  675.          *   
  676.          * @param fieldName  
  677.          *            hbm对象属性名称或字段名  
  678.          * @param minTime  
  679.          *            开始时间  
  680.          * @param maxTime  
  681.          *            结果时间  
  682.          */  
  683.         public DmlHelper addTimeRange(String fieldName, Date minTime, Date maxTime) {  
  684.             if (minTime != null) {  
  685.                 dmlCmd.append(" and ").append(fieldName).append(">? ");  
  686.                 paramList.add(minTime);  
  687.             }  
  688.   
  689.             if (maxTime != null) {  
  690.                 dmlCmd.append(" and ").append(fieldName).append("<? ");  
  691.                 paramList.add(maxTime);  
  692.             }  
  693.             return this;  
  694.         }  
  695.   
  696.         public <D> Pagination<D> findPagin(int pageIndex, int pageSize) {  
  697.             String hql = dmlCmd.toString();  
  698.             Object[] allParams = new Object[paramList.size()];  
  699.             int i = 0;  
  700.             for (Object o : paramList) {  
  701.                 allParams[i++] = o;  
  702.             }  
  703.             return findPagination(hql, pageIndex, pageSize, allParams);  
  704.         }  
  705.   
  706.     }  
  707.   
  708. }  
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.xxx.finance.dao.BaseDao;
import com.xxx.finance.utils.HibernateHandler;
import com.xxx.finance.utils.ObjectUtil;
import com.xxx.finance.utils.Pagination;

/**
 * @author 
 */
@Repository
public class BaseDaoImpl<T> implements BaseDao<T> {

    protected Class<T> entityClazz;

    protected SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
    public BaseDaoImpl() {
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            this.entityClazz = (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0];
        } else {
            this.entityClazz = null;
        }
    }

    @Resource
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @SuppressWarnings("unchecked")
    public Object save(Object entity) {
        return (T) getSession().save(entity);
    }

    public void delete(Object entity) {

        getSession().delete(entity);
    }

    public void update(Object entity) {

        getSession().update(entity);
    }

    public void saveOrUpdate(Object entity) {

        getSession().saveOrUpdate(entity);
    }

    public void saveAll(Collection<?> entities) {

        for (@SuppressWarnings("rawtypes")
        Iterator localIterator = entities.iterator(); localIterator.hasNext();) {
            Object entity = localIterator.next();
            getSession().save(entity);
        }
    }

    public void deleteAll(Collection<?> entities) {

        for (@SuppressWarnings("rawtypes")
        Iterator localIterator = entities.iterator(); localIterator.hasNext();) {
            Object entity = localIterator.next();
            getSession().delete(entity);
        }
    }

    public void updateAll(Collection<?> entities) {

        for (@SuppressWarnings("rawtypes")
        Iterator localIterator = entities.iterator(); localIterator.hasNext();) {
            Object entity = localIterator.next();
            getSession().update(entity);
        }
    }

    public void saveOrUpdateAll(Collection<?> entities) {

        for (@SuppressWarnings("rawtypes")
        Iterator localIterator = entities.iterator(); localIterator.hasNext();) {
            Object entity = localIterator.next();
            getSession().saveOrUpdate(entity);
        }
    }

    @SuppressWarnings({ "unchecked", "hiding" })
    public <T> T get(Class<T> entityClass, Serializable id) {

        return (T) getSession().get(entityClass, id);
    }

    @SuppressWarnings({ "unchecked", "rawtypes", "hiding" })
    public <T> T get(CharSequence queryString, Object... params) {

        Query qry = getSession().createQuery(queryString.toString());
        for (int i = 0; i < params.length; ++i) {
            qry.setParameter(i, params[i]);
        }
        List list = qry.setMaxResults(1).list();
        if (list.isEmpty())
            return null;
        return (T) list.get(0);
    }

    @SuppressWarnings({ "unchecked", "hiding" })
    public <T> T get(CharSequence queryString, Map<String, Object> params) {

        Query qry = getSession().createQuery(queryString.toString());
        setParameter(qry, params);
        @SuppressWarnings("rawtypes")
        List list = qry.setMaxResults(1).list();
        if (list.isEmpty())
            return null;
        return (T) list.get(0);
    }

    @SuppressWarnings({ "unchecked", "hiding" })
    public <T> List<T> findList(CharSequence queryString, Object... params) {
        Query query = getSession().createQuery(queryString.toString());
        for (int i = 0; i < params.length; ++i) {
            query.setParameter(i, params[i]);
        }
        return query.list();
    }

    @SuppressWarnings({ "unchecked", "hiding" })
    public <T> List<T> findList(CharSequence queryString, Map<String, Object> params) {
        Query query = getSession().createQuery(queryString.toString());
        setParameter(query, params);
        return query.list();
    }

    @SuppressWarnings({ "unchecked", "hiding" })
    public <T> Pagination<T> findPagination(CharSequence queryString, int pageIndex, int pageSize, Object... params) {
        Query query = getSession().createQuery(queryString.toString());

        if ((pageSize > 0) && (pageIndex > 0)) {
            query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
            query.setMaxResults(pageSize);
        }

        for (int i = 0; i < params.length; ++i) {
            query.setParameter(i, params[i]);
        }
        @SuppressWarnings("rawtypes")
        List items = query.list();
        long rowsCount = 0L;

        if ((pageSize > 0) && (pageIndex > 0)) {
            String hql = parseSelectCount(queryString.toString());
            rowsCount = ((Long) get(hql, params)).longValue();
        } else {
            rowsCount = items.size();
        }

        @SuppressWarnings("rawtypes")
        Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);
        pagination.setItems(items);
        return pagination;
    }

    @SuppressWarnings({ "unchecked", "hiding" })
    public <T> Pagination<T> findPagination(CharSequence queryString, Map<String, Object> params, int pageIndex,
            int pageSize) {
        Query query = getSession().createQuery(queryString.toString());

        if ((pageSize > 0) && (pageIndex > 0)) {
            query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
            query.setMaxResults(pageSize);
        }

        setParameter(query, params);
        @SuppressWarnings({ "rawtypes" })
        List items = query.list();
        long rowsCount = 0L;

        if ((pageSize > 0) && (pageIndex > 0)) {
            String hql = parseSelectCount(queryString.toString());
            rowsCount = ((Long) get(hql, params)).longValue();
        } else {
            rowsCount = items.size();
        }

        @SuppressWarnings("rawtypes")
        Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);
        pagination.setItems(items);
        return pagination;
    }

    @SuppressWarnings({ "unchecked", "hiding" })
    public <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString, int pageIndex,
            int pageSize, Object... params) {
        Query query = getSession().createQuery(queryString.toString());

        if ((pageSize > 0) && (pageIndex > 0)) {
            query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
            query.setMaxResults(pageSize);
        }

        for (int i = 0; i < params.length; ++i) {
            query.setParameter(i, params[i]);
        }
        @SuppressWarnings("rawtypes")
        List items = query.list();
        long rowsCount = 0L;

        if ((pageSize > 0) && (pageIndex > 0)) {
            rowsCount = ((Long) get(countString, params)).longValue();
        } else
            rowsCount = items.size();

        @SuppressWarnings("rawtypes")
        Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);
        pagination.setItems(items);
        return pagination;
    }

    @SuppressWarnings({ "unchecked", "hiding" })
    public <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString,
            Map<String, Object> params, int pageIndex, int pageSize) {
        Query query = getSession().createQuery(queryString.toString());

        if ((pageSize > 0) && (pageIndex > 0)) {
            query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
            query.setMaxResults(pageSize);
        }

        setParameter(query, params);
        @SuppressWarnings("rawtypes")
        List items = query.list();
        long rowsCount = 0L;

        if ((pageSize > 0) && (pageIndex > 0)) {
            rowsCount = ((Long) get(countString, params)).longValue();
        } else
            rowsCount = items.size();

        @SuppressWarnings("rawtypes")
        Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);
        pagination.setItems(items);
        return pagination;
    }

    @SuppressWarnings({ "serial", "unchecked", "hiding" })
    public <T> Pagination<T> findSqlPagination(CharSequence queryString, final CharSequence countString,
            final Map<String, Object> params, int pageIndex, int pageSize) {
        SQLQuery query = getSession().createSQLQuery(queryString.toString());
        query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

        if ((pageSize > 0) && (pageIndex > 0)) {
            query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
            query.setMaxResults(pageSize);
        }
        if ((params != null) && (!(params.isEmpty()))) {
            setParameter(query, params);
        }
        @SuppressWarnings("rawtypes")
        List items = query.list();
        BigInteger rowsCount = BigInteger.valueOf(0L);

        if ((pageSize > 0) && (pageIndex > 0)) {
            rowsCount = (BigInteger) executeQuery(new HibernateHandler() {
                public Object doInHibernate(Session session) {
                    SQLQuery query = session.createSQLQuery(countString.toString());
                    if ((params != null) && (!(params.isEmpty()))) {
                        setParameter(query, params);
                    }
                    return query.uniqueResult();
                }
            });
        }

        @SuppressWarnings("rawtypes")
        Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount.intValue());
        pagination.setItems(items);
        return pagination;
    }

    public Object executeQuery(HibernateHandler handler) {
        return handler.doInHibernate(getSession());
    }

    public void execute(String hql) {
        executeUpdate(hql);
    }

    public void execute(HibernateHandler handler) {
        executeUpdate(handler);
    }

    public void executeSql(String sql) {
        executeSqlUpdate(sql);
    }

    public int executeSqlUpdate(String sql) {
        return getSession().createSQLQuery(sql).executeUpdate();
    }

    public int executeUpdate(String hql) {
        return getSession().createQuery(hql).executeUpdate();
    }

    public Object executeUpdate(HibernateHandler handler) {
        return handler.doInHibernate(getSession());
    }

    protected Query setParameter(Query query, Map<String, Object> parameterMap) {
        for (@SuppressWarnings("rawtypes")
        Iterator iterator = parameterMap.keySet().iterator(); iterator.hasNext();) {
            String key = (String) iterator.next();
            query.setParameter(key, parameterMap.get(key));
        }
        return query;
    }

    protected boolean followWithWord(String s, String sub, int pos) {
        int i = 0;
        for (; (pos < s.length()) && (i < sub.length()); ++i) {
            if (s.charAt(pos) != sub.charAt(i))
                return false;
            ++pos;
        }

        if (i < sub.length()) {
            return false;
        }

        if (pos >= s.length()) {
            return true;
        }
        return (!(isAlpha(s.charAt(pos))));
    }

    protected String parseSelectCount(String queryString) {
        String hql = queryString.toLowerCase();
        int noBlankStart = 0;
        for (int len = hql.length(); noBlankStart < len; ++noBlankStart) {
            if (hql.charAt(noBlankStart) > ' ') {
                break;
            }
        }

        int pair = 0;

        if (!(followWithWord(hql, "select", noBlankStart))) {
            pair = 1;
        }
        int fromPos = -1;
        for (int i = noBlankStart; i < hql.length();) {
            if (followWithWord(hql, "select", i)) {
                ++pair;
                i += "select".length();
            } else if (followWithWord(hql, "from", i)) {
                --pair;
                if (pair == 0) {
                    fromPos = i;
                    break;
                }
                i += "from".length();
            } else {
                ++i;
            }
        }
        if (fromPos == -1) {
            throw new IllegalArgumentException("parse count sql error, check your sql/hql");
        }

        String countHql = "select count(*) " + queryString.substring(fromPos);
        return countHql;
    }

    protected boolean isAlpha(char c) {
        return ((c == '_') || (('0' <= c) && (c <= '9')) || (('a' <= c) && (c <= 'z')) || (('A' <= c) && (c <= 'Z')));
    }

    public void delete(Serializable id) {
        T entity = getById(id);
        delete(entity);
    }

    public void delete(List<T> entitys) {
        for (T entity : entitys) {
            delete(entity);
        }
    }

    public T getById(Serializable id) {
        if (id == null)
            return null;

        return (T) get(entityClazz, id);
    }

    @Override
    public T saveEntity(T o) {
        saveOrUpdate(o);
        return o;
    }

    @Override
    public void save(List<T> list) {
        saveOrUpdateAll(list);
    }

    @Override
    public T insert(T entity) {
        save(entity);
        return entity;
    }

    @Override
    public void insert(List<T> entitys) {
        for (T entity : entitys) {
            save(entity);
        }
    }

    @Override
    public void update(List<T> entitys) {
        for (T entity : entitys) {
            update(entity);
        }
    }

    @Override
    public List<T> findByProperty(String name, Object value) {
        String hql = "from  " + entityClazz.getSimpleName() + " where " + name + "=? ";
        return findList(hql, value);
    }

    @Override
    public List<T> findByProperty(Map<String, Object> conditionMap) {
        StringBuilder hql = new StringBuilder();
        hql.append("from  " + entityClazz.getSimpleName());
        if (!conditionMap.isEmpty()) {
            Iterator<String> it = conditionMap.keySet().iterator();
            String key = it.next();
            hql.append(" where  " + key + "=:" + key);
            while (it.hasNext()) {
                key = it.next();
                hql.append(" and  " + key + "=:" + key);
            }
        }
        return findList(hql.toString(), conditionMap);
    }

    @Override
    public <V> List<V> findListByMax(final CharSequence queryString, final int maxResults, final Object... params) {
        @SuppressWarnings({ "unchecked", "serial" })
        List<V> list = (List<V>) executeQuery(new HibernateHandler() {
            @Override
            public List<V> doInHibernate(Session paramSession) {
                try {
                    Query query = paramSession.createQuery(queryString.toString());
                    for (int i = 0; i < params.length; ++i) {
                        query.setParameter(i, params[i]);
                    }
                    return query.setMaxResults(maxResults).list();
                } catch (RuntimeException re) {
                    throw re;
                }
            }
        });
        return list;
    }

    @Override
    public <V> List<V> findListByMax(final CharSequence queryString, final int maxResults,
            final Map<String, Object> params) {
        @SuppressWarnings({ "unchecked", "serial" })
        List<V> list = (List<V>) executeQuery(new HibernateHandler() {
            @Override
            public List<V> doInHibernate(Session paramSession) {
                try {
                    Query query = paramSession.createQuery(queryString.toString());
                    for (Iterator<String> iterator = params.keySet().iterator(); iterator.hasNext();) {
                        String key = iterator.next();
                        query.setParameter(key, params.get(key));
                    }
                    return query.setMaxResults(maxResults).list();
                } catch (RuntimeException re) {
                    throw re;
                }
            }

        });
        return list;
    }

    /**
     * HQL/SQL之数据操作命令(DML)拼接辅助类
     * 
     * @author PanJun
     * @deprecated by fu.zhanghua
     * 
     */
    public class DmlHelper {

        private ThreadLocal<Calendar> cal = new ThreadLocal<Calendar>() {
            @Override
            protected Calendar initialValue() {
                return Calendar.getInstance();
            }
        };

        /** HQL/SQL参数 */
        public final List<Object> paramList = new ArrayList<Object>();
        /** HQL/SQL语句 */
        public final StringBuilder dmlCmd = new StringBuilder();

        public DmlHelper() {
        }

        public DmlHelper(CharSequence dml, Object... params) {
            if (dml != null) {
                dmlCmd.append(dml);
                for (Object o : params) {
                    paramList.add(o);
                }
            }
        }

        @Override
        public String toString() {
            return "dml=" + dmlCmd + ", params=" + paramList;
        }

        public DmlHelper append(CharSequence dmlPart, Object... params) {
            if (dmlPart != null) {
                dmlCmd.append(" ").append(dmlPart);
                for (Object o : params) {
                    paramList.add(o);
                }
            }
            return this;
        }

        public DmlHelper addEqual(String fieldName, Object value, Object... nullVal) {
            if (value == null || fieldName == null) {
                return this;
            }

            if (value instanceof String) {
                value = value.toString().trim();
                if ("".equals(value)) {
                    return this;
                }
            }

            for (Object NULL : nullVal) {
                if (NULL == value) {
                    return this;
                }

                if (value.equals(NULL)) {
                    return this;
                }
            }

            dmlCmd.append(" and ").append(fieldName).append("=? ");
            paramList.add(value);
            return this;
        }

        public DmlHelper addLikeAll(String name, String value) {
            if (null == value || null == name)
                return this;

            value = "%" + value.trim().toLowerCase() + "%";
            dmlCmd.append(" and lower(").append(name).append(") like ? ");
            paramList.add(value);
            return this;
        }

        /**
         * 清除时间里的时分秒,只留日期
         * 
         * @param date
         * @return new date
         */
        private void clearTime(Calendar calendar) {
            int y = calendar.get(Calendar.YEAR);
            int m = calendar.get(Calendar.MONTH);
            int d = calendar.get(Calendar.DAY_OF_MONTH);
            calendar.clear();
            calendar.set(Calendar.YEAR, y);
            calendar.set(Calendar.MONTH, m);
            calendar.set(Calendar.DAY_OF_MONTH, d);
        }

        /**
         * 添加开始日期、结束日期(注意时分秒不记入查询条件)查询条件,包含开始日期和结束日期
         * 
         * @param fieldName
         *            hbm对象属性名称或字段名
         * @param minDay
         *            开始日期
         * @param maxDay
         *            结果日期
         */
        public DmlHelper addDayRange(String fieldName, Date minDay, Date maxDay) {
            Calendar calendar = cal.get();
            if (minDay != null) {
                calendar.setTime(minDay);
                clearTime(calendar);
                calendar.add(Calendar.SECOND, -1);
                dmlCmd.append(" and ").append(fieldName).append(">? ");
                paramList.add(calendar.getTime());
            }

            if (maxDay != null) {
                calendar.setTime(maxDay);
                clearTime(calendar);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                dmlCmd.append(" and ").append(fieldName).append("<? ");
                paramList.add(calendar.getTime());
            }
            return this;
        }

        /**
         * 添加开始时间、结束时间查询条件,包含开始时间和结束时间
         * 
         * @param fieldName
         *            hbm对象属性名称或字段名
         * @param minTime
         *            开始时间
         * @param maxTime
         *            结果时间
         */
        public DmlHelper addDayRange(String fieldName, String minTime, String maxTime) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date start_ = null, end_ = null;
            if (ObjectUtil.hasText(minTime) && ObjectUtil.hasText(maxTime)) {
                try {
                    start_ = sdf.parse(minTime);
                    end_ = sdf.parse(maxTime);
                } catch (ParseException e) {
                }
            }

            return addTimeRange(fieldName, start_, end_);
        }

        /**
         * 添加开始时间、结束时间查询条件,包含开始时间和结束时间
         * 
         * @param fieldName
         *            hbm对象属性名称或字段名
         * @param minTime
         *            开始时间
         * @param maxTime
         *            结果时间
         */
        public DmlHelper addTimeRange(String fieldName, Date minTime, Date maxTime) {
            if (minTime != null) {
                dmlCmd.append(" and ").append(fieldName).append(">? ");
                paramList.add(minTime);
            }

            if (maxTime != null) {
                dmlCmd.append(" and ").append(fieldName).append("<? ");
                paramList.add(maxTime);
            }
            return this;
        }

        public <D> Pagination<D> findPagin(int pageIndex, int pageSize) {
            String hql = dmlCmd.toString();
            Object[] allParams = new Object[paramList.size()];
            int i = 0;
            for (Object o : paramList) {
                allParams[i++] = o;
            }
            return findPagination(hql, pageIndex, pageSize, allParams);
        }

    }

}

HibernateHandler.java

  1. import java.io.Serializable;  
  2.   
  3. import org.hibernate.Session;  
  4.   
  5. public abstract interface HibernateHandler extends Serializable {  
  6.     public abstract Object doInHibernate(Session paramSession);  
  7. }  
import java.io.Serializable;

import org.hibernate.Session;

public abstract interface HibernateHandler extends Serializable {
    public abstract Object doInHibernate(Session paramSession);
}

Pagination.java

  1. import java.io.Serializable;  
  2. import java.util.List;  
  3.   
  4. /**  
  5.  * 数据分页类  
  6.  *   
  7.  * @author GST  
  8.  * @version 1.0, 2006-12-30  
  9.  */  
  10.   
  11. public class Pagination<T> implements Serializable {  
  12.   
  13.     private static final long serialVersionUID = -5884976706259160221L;  
  14.     /**  
  15.      * 上一页  
  16.      */  
  17.     private long preIndex;  
  18.     /**  
  19.      * 当前页  
  20.      */  
  21.     private long curIndex;  
  22.     /**  
  23.      * 下一页  
  24.      */  
  25.     private long nextIndex;  
  26.     /**  
  27.      * 每页条数  
  28.      */  
  29.     private long pageSize;  
  30.     /**  
  31.      * 总条数  
  32.      */  
  33.     private long rowsCount;  
  34.   
  35.     public void setPreIndex(long preIndex) {  
  36.         this.preIndex = preIndex;  
  37.     }  
  38.   
  39.     public void setCurIndex(long curIndex) {  
  40.         this.curIndex = curIndex;  
  41.     }  
  42.   
  43.     public void setNextIndex(long nextIndex) {  
  44.         this.nextIndex = nextIndex;  
  45.     }  
  46.   
  47.     public void setPageSize(long pageSize) {  
  48.         this.pageSize = pageSize;  
  49.     }  
  50.   
  51.     /**  
  52.      * 总页数  
  53.      */  
  54.     private long pagesCount;  
  55.     /**  
  56.      * 对象列表  
  57.      */  
  58.     private List<T> items;  
  59.   
  60.     /**  
  61.      *   
  62.      * 分页类构建函数  
  63.      *   
  64.      */  
  65.     public Pagination() {  
  66.         updateInfo(0, 0, 0);  
  67.     }  
  68.   
  69.     /**  
  70.      *   
  71.      * 分页类构建函数  
  72.      *   
  73.      * @param pageIndex  
  74.      *            当前页码  
  75.      * @param pageSize  
  76.      *            每页记录数  
  77.      */  
  78.     public Pagination(long pageIndex, long pageSize) {  
  79.         updateInfo(pageIndex, pageSize, 0);  
  80.     }  
  81.   
  82.     /**  
  83.      * 分页类构建函数  
  84.      *   
  85.      * @param pageIndex  
  86.      *            当前页码  
  87.      * @param pageSize  
  88.      *            每页记录数  
  89.      * @param rowsCount  
  90.      *            记录总数  
  91.      */  
  92.     public Pagination(long pageIndex, long pageSize, long rowsCount) {  
  93.         updateInfo(pageIndex, pageSize, rowsCount);  
  94.     }  
  95.   
  96.     /**  
  97.      * 获取当前面记录  
  98.      *   
  99.      * @return  
  100.      */  
  101.     public List<T> getItems() {  
  102.         return items;  
  103.     }  
  104.   
  105.     /**  
  106.      * 设置当前页记录  
  107.      *   
  108.      * @param items  
  109.      */  
  110.     public void setItems(List<T> items) {  
  111.         this.items = items;  
  112.     }  
  113.   
  114.     /**  
  115.      * 获取当前页码  
  116.      *   
  117.      * @return  
  118.      */  
  119.     public long getCurIndex() {  
  120.         return curIndex;  
  121.     }  
  122.   
  123.     /**  
  124.      * 获取下一页码  
  125.      *   
  126.      * @return  
  127.      */  
  128.     public long getNextIndex() {  
  129.         return nextIndex;  
  130.     }  
  131.   
  132.     /**  
  133.      * 获取总页数  
  134.      *   
  135.      * @return  
  136.      */  
  137.     public long getPagesCount() {  
  138.         return pagesCount;  
  139.     }  
  140.   
  141.     /**  
  142.      * 获取每页记录数  
  143.      *   
  144.      * @return  
  145.      */  
  146.     public long getPageSize() {  
  147.         return pageSize;  
  148.     }  
  149.   
  150.     /**  
  151.      * 获取上一页码  
  152.      *   
  153.      * @return  
  154.      */  
  155.     public long getPreIndex() {  
  156.         return preIndex;  
  157.     }  
  158.   
  159.     /**  
  160.      * 获取总记录数  
  161.      *   
  162.      * @return  
  163.      */  
  164.     public long getRowsCount() {  
  165.         return rowsCount;  
  166.     }  
  167.   
  168.     /**  
  169.      * 获取首页码  
  170.      *   
  171.      * @return  
  172.      */  
  173.     public long getFirstIndex() {  
  174.         return 1;  
  175.     }  
  176.   
  177.     /**  
  178.      * 获取末页码  
  179.      *   
  180.      * @return  
  181.      */  
  182.     public long getLastIndex() {  
  183.         return pagesCount;  
  184.     }  
  185.   
  186.     private void updateInfo(long pageIndex, long pageSize, long rowsCount) {  
  187.   
  188.         if (pageSize > 0) {  
  189.   
  190.             this.curIndex = pageIndex;  
  191.             this.rowsCount = rowsCount;  
  192.             this.pageSize = pageSize;  
  193.   
  194.             // 确定页数  
  195.             pagesCount = (rowsCount + pageSize - 1) / pageSize;  
  196.             // 确定当前页码  
  197.             if (curIndex <= 0)  
  198.                 curIndex = 1;  
  199.             if (curIndex > pagesCount)  
  200.                 curIndex = pagesCount;  
  201.             // 确定下一页码  
  202.             nextIndex = curIndex + 1;  
  203.             if (nextIndex > pagesCount)  
  204.                 nextIndex = pagesCount;  
  205.             // 确定上一页码  
  206.             preIndex = curIndex - 1;  
  207.             if (preIndex <= 0)  
  208.                 preIndex = 1;  
  209.         } else {  
  210.             this.preIndex = 1;  
  211.             this.curIndex = 1;  
  212.             this.nextIndex = 1;  
  213.             this.pageSize = 0;  
  214.             this.pagesCount = 1;  
  215.         }  
  216.     }  
  217.   
  218.     /**  
  219.      * 设置总记录数  
  220.      *   
  221.      * @param rowsCount  
  222.      */  
  223.     public void setRowsCount(long rowsCount) {  
  224.         updateInfo(curIndex, pageSize, rowsCount);  
  225.     }  
  226.   
  227.     /**  
  228.      * 设置总页数  
  229.      *   
  230.      * @param pagesCount  
  231.      */  
  232.     public void setPagesCount(long pagesCount) {  
  233.         this.pagesCount = pagesCount;  
  234.     }  
  235.   
  236. }  
import java.io.Serializable;
import java.util.List;

/**
 * 数据分页类
 * 
 * @author GST
 * @version 1.0, 2006-12-30
 */

public class Pagination<T> implements Serializable {

    private static final long serialVersionUID = -5884976706259160221L;
    /**
     * 上一页
     */
    private long preIndex;
    /**
     * 当前页
     */
    private long curIndex;
    /**
     * 下一页
     */
    private long nextIndex;
    /**
     * 每页条数
     */
    private long pageSize;
    /**
     * 总条数
     */
    private long rowsCount;

    public void setPreIndex(long preIndex) {
        this.preIndex = preIndex;
    }

    public void setCurIndex(long curIndex) {
        this.curIndex = curIndex;
    }

    public void setNextIndex(long nextIndex) {
        this.nextIndex = nextIndex;
    }

    public void setPageSize(long pageSize) {
        this.pageSize = pageSize;
    }

    /**
     * 总页数
     */
    private long pagesCount;
    /**
     * 对象列表
     */
    private List<T> items;

    /**
     * 
     * 分页类构建函数
     * 
     */
    public Pagination() {
        updateInfo(0, 0, 0);
    }

    /**
     * 
     * 分页类构建函数
     * 
     * @param pageIndex
     *            当前页码
     * @param pageSize
     *            每页记录数
     */
    public Pagination(long pageIndex, long pageSize) {
        updateInfo(pageIndex, pageSize, 0);
    }

    /**
     * 分页类构建函数
     * 
     * @param pageIndex
     *            当前页码
     * @param pageSize
     *            每页记录数
     * @param rowsCount
     *            记录总数
     */
    public Pagination(long pageIndex, long pageSize, long rowsCount) {
        updateInfo(pageIndex, pageSize, rowsCount);
    }

    /**
     * 获取当前面记录
     * 
     * @return
     */
    public List<T> getItems() {
        return items;
    }

    /**
     * 设置当前页记录
     * 
     * @param items
     */
    public void setItems(List<T> items) {
        this.items = items;
    }

    /**
     * 获取当前页码
     * 
     * @return
     */
    public long getCurIndex() {
        return curIndex;
    }

    /**
     * 获取下一页码
     * 
     * @return
     */
    public long getNextIndex() {
        return nextIndex;
    }

    /**
     * 获取总页数
     * 
     * @return
     */
    public long getPagesCount() {
        return pagesCount;
    }

    /**
     * 获取每页记录数
     * 
     * @return
     */
    public long getPageSize() {
        return pageSize;
    }

    /**
     * 获取上一页码
     * 
     * @return
     */
    public long getPreIndex() {
        return preIndex;
    }

    /**
     * 获取总记录数
     * 
     * @return
     */
    public long getRowsCount() {
        return rowsCount;
    }

    /**
     * 获取首页码
     * 
     * @return
     */
    public long getFirstIndex() {
        return 1;
    }

    /**
     * 获取末页码
     * 
     * @return
     */
    public long getLastIndex() {
        return pagesCount;
    }

    private void updateInfo(long pageIndex, long pageSize, long rowsCount) {

        if (pageSize > 0) {

            this.curIndex = pageIndex;
            this.rowsCount = rowsCount;
            this.pageSize = pageSize;

            // 确定页数
            pagesCount = (rowsCount + pageSize - 1) / pageSize;
            // 确定当前页码
            if (curIndex <= 0)
                curIndex = 1;
            if (curIndex > pagesCount)
                curIndex = pagesCount;
            // 确定下一页码
            nextIndex = curIndex + 1;
            if (nextIndex > pagesCount)
                nextIndex = pagesCount;
            // 确定上一页码
            preIndex = curIndex - 1;
            if (preIndex <= 0)
                preIndex = 1;
        } else {
            this.preIndex = 1;
            this.curIndex = 1;
            this.nextIndex = 1;
            this.pageSize = 0;
            this.pagesCount = 1;
        }
    }

    /**
     * 设置总记录数
     * 
     * @param rowsCount
     */
    public void setRowsCount(long rowsCount) {
        updateInfo(curIndex, pageSize, rowsCount);
    }

    /**
     * 设置总页数
     * 
     * @param pagesCount
     */
    public void setPagesCount(long pagesCount) {
        this.pagesCount = pagesCount;
    }

}

ObjectUtil.java

  1. import java.lang.reflect.InvocationTargetException;  
  2. import java.lang.reflect.Method;  
  3. import java.lang.reflect.ParameterizedType;  
  4. import java.lang.reflect.Type;  
  5. import java.util.ArrayList;  
  6. import java.util.Date;  
  7. import java.util.HashMap;  
  8. import java.util.List;  
  9. import java.util.Map;  
  10.   
  11. /**  
  12.  * @author Administrator  
  13.  * @date 2013-4-27 上午10:51:14  
  14.  * @since 1.0  
  15.  */  
  16. public class ObjectUtil {  
  17.     /**  
  18.      * <p>  
  19.      * 把原对象的属性值拷贝到目标对象,并返回目标对象.<b>拷贝空值</b>.  
  20.      * </p>  
  21.      *   
  22.      * @param source  
  23.      *            数据来源对象  
  24.      * @param target  
  25.      *            目标对象  
  26.      * @return 目标对象  
  27.      */  
  28.     public static <T> T copyPropVal(Object source, T target) {  
  29.         return copyPropVal(source, target, true);  
  30.     }  
  31.   
  32.     /**  
  33.      * 把原对象的属性值拷贝到目标对象,并返回目标对象;不处理复合属性;<b>不拷贝空值</b>  
  34.      *   
  35.      * @param <T>  
  36.      * @param source  
  37.      * @param target  
  38.      * @return 目标对象  
  39.      */  
  40.     public static <T> T copyNotNullPropVal(Object source, T target) {  
  41.         return copyPropVal(source, target, false);  
  42.     }  
  43.   
  44.     private static Object callGetter(Object o, List<Method> getterList) {  
  45.         if (getterList == null || o == null)  
  46.             return null;  
  47.   
  48.         for (Method m : getterList) {  
  49.             if (!m.getReturnType().equals(void.class) && m.getParameterTypes().length == 0) {  
  50.                 try {  
  51.                     return m.invoke(o);  
  52.                 } catch (Exception e) {  
  53.                 }  
  54.             }  
  55.         }  
  56.         return null;  
  57.     }  
  58.   
  59.     private static void callSetter(Object o, Object val, List<Method> setterList) {  
  60.         if (setterList == null || o == null)  
  61.             return;  
  62.   
  63.         for (Method m : setterList) {  
  64.             if (m.getReturnType().equals(void.class) && m.getParameterTypes().length == 1) {  
  65.                 try {  
  66.                     m.invoke(o, val);  
  67.                     return;  
  68.                 } catch (Exception e) {  
  69.                 }  
  70.             }  
  71.         }  
  72.     }  
  73.   
  74.     /**  
  75.      * 见prepareToSave,空值默认<b></b>覆盖  
  76.      *   
  77.      * @param savingEntity  
  78.      *            要保存到数据库的实体对象  
  79.      * @param valueEntity  
  80.      *            数值实体  
  81.      * @param userId  
  82.      *            当前用户ID  
  83.      * @return 处理以后的参数savingEntity  
  84.      */  
  85.     public static <T> T prepareToSave(T savingEntity, Object valueEntity, String userId) {  
  86.         return prepareToSave(savingEntity, valueEntity, userId, false);  
  87.     }  
  88.   
  89.     /**  
  90.      * 在保存savingEntity实体之前,完成对savingEntity字段值的设置操作,具体如下:<br>  
  91.      * 1)设置savingEntity的通用字段getDisabled(isDisabled), getCreateTime,  
  92.      * getCreatedBy,setCreateTime,setCreateBy,setUpdateTime,setUpdateBy 2)拷贝  
  93.      * 数值实体valueEntity 所有属性值到savingEntity相应属性<br>  
  94.      * 本方法返回待保存的实体  
  95.      *   
  96.      * @param <T>  
  97.      * @param savingEntity  
  98.      *            要保存到数据库的实体对象  
  99.      * @param valueEntity  
  100.      *            数值实体  
  101.      * @param userId  
  102.      *            当前用户ID  
  103.      * @param copyNull  
  104.      *            是否拷贝空值  
  105.      * @return 处理以后的参数savingEntity  
  106.      */  
  107.     public static <T> T prepareToSave(T savingEntity, Object valueEntity, String userId, boolean copyNull) {  
  108.         if (savingEntity == null)  
  109.             return savingEntity;  
  110.   
  111.         HashMap<String, List<Method>> methodMap = new HashMap<String, List<Method>>();  
  112.         for (Method m : savingEntity.getClass().getMethods()) {  
  113.             List<Method> list = methodMap.get(m.getName());  
  114.             if (list == null) {  
  115.                 list = new ArrayList<Method>();  
  116.                 methodMap.put(m.getName(), list);  
  117.             }  
  118.             list.add(m);  
  119.         }  
  120.   
  121.         Object createTime = callGetter(savingEntity, methodMap.get("getCreateTime"));  
  122.         Object createBy = callGetter(savingEntity, methodMap.get("getCreateBy"));  
  123.   
  124.         copyPropVal(valueEntity, savingEntity, copyNull);  
  125.   
  126.         Date now = new Date();  
  127.         if (createTime == null)  
  128.             createTime = now;  
  129.         if (createBy == null)  
  130.             createBy = userId;  
  131.   
  132.         // ~~exam or ERP~~  
  133.         Object creationDate = callGetter(savingEntity, methodMap.get("getCreationDate"));  
  134.         Object createdBy = callGetter(savingEntity, methodMap.get("getCreatedBy"));  
  135.         if (createdBy == null)  
  136.             createdBy = userId;  
  137.         if (creationDate == null)  
  138.             creationDate = now;  
  139.         // ~~exam or ERP~~  
  140.   
  141.         Object disabled = callGetter(savingEntity, methodMap.get("getDisabled"));  
  142.         if (disabled == null)  
  143.             disabled = callGetter(savingEntity, methodMap.get("isDisabled"));  
  144.         if (disabled == null)  
  145.             callSetter(savingEntity, false, methodMap.get("setDisabled"));  
  146.   
  147.         callSetter(savingEntity, createBy, methodMap.get("setCreateBy"));  
  148.         callSetter(savingEntity, createTime, methodMap.get("setCreateTime"));  
  149.         callSetter(savingEntity, now, methodMap.get("setUpdateTime"));  
  150.         callSetter(savingEntity, userId, methodMap.get("setUpdateBy"));  
  151.   
  152.         // ~~exam or ERP~~  
  153.         callSetter(savingEntity, createdBy, methodMap.get("setCreatedBy"));  
  154.         callSetter(savingEntity, creationDate, methodMap.get("setCreationDate"));  
  155.         callSetter(savingEntity, now, methodMap.get("setLastUpdateDate"));  
  156.         callSetter(savingEntity, userId, methodMap.get("setLastUpdatedBy"));  
  157.         callSetter(savingEntity, userId, methodMap.get("setLastUpdateLogin"));  
  158.         // ~~exam or ERP~~  
  159.         return savingEntity;  
  160.     }  
  161.   
  162.     private static boolean isZteClass(Type type) {  
  163.         if (!(type instanceof Class))  
  164.             return false;  
  165.         DataObjectDescriptor annotation = ((Class<?>) type).getAnnotation(DataObjectDescriptor.class);  
  166.         return annotation != null;  
  167.     }  
  168.   
  169.     @SuppressWarnings({ "unchecked", "rawtypes" })  
  170.     private static Map<??> makeTargetMap(Map<??> source, Type keyType, Type valType, boolean copyNull)  
  171.             throws Exception {  
  172.         if (!(keyType instanceof Class))  
  173.             throw new UnsupportedOperationException("makeTargetMap " + keyType);  
  174.   
  175.         Class<?> keyClzz = (Class<?>) keyType;  
  176.   
  177.         Map result = new HashMap();  
  178.         for (Object k : source.keySet()) {  
  179.             Object srcVal = source.get(k);  
  180.             Object value = srcVal;  
  181.             Object key = k;  
  182.             if (isZteClass(keyClzz))  
  183.                 key = copyNotNullPropVal(k, keyClzz.newInstance());  
  184.   
  185.             if (isZteClass(valType)) {  
  186.                 value = copyPropVal(srcVal, ((Class<?>) valType).newInstance(), copyNull);  
  187.             } else if (checkCopyAsList(srcVal, valType)) {  
  188.                 Type actualType = ((ParameterizedType) valType).getActualTypeArguments()[0];  
  189.                 value = makeTargetList((List<?>) srcVal, (Class<?>) actualType, copyNull);  
  190.             } else if (checkCopyAsMap(srcVal, valType)) {  
  191.                 ParameterizedType prmType = (ParameterizedType) valType;  
  192.                 Type subKeyType = prmType.getActualTypeArguments()[0];  
  193.                 Type subValType = prmType.getActualTypeArguments()[1];  
  194.                 value = makeTargetMap((Map<??>) srcVal, subKeyType, subValType, copyNull);  
  195.             }  
  196.             result.put(key, value);  
  197.         }  
  198.         return result;  
  199.     }  
  200.   
  201.     /**  
  202.      * 把原对象的属性值拷贝到目标对象,并返回目标对象;不处理复合属性,可控制是否拷贝空值  
  203.      *   
  204.      * @param <T>  
  205.      * @param source  
  206.      * @param target  
  207.      * @param copyNull  
  208.      *            是否拷贝空值  
  209.      * @return 目标对象  
  210.      */  
  211.     public static <T> T copyPropVal(Object source, T target, boolean copyNull) {  
  212.         if (source == null || target == null)  
  213.             return target;  
  214.   
  215.         Map<String, Method> getterMap = new HashMap<String, Method>();  
  216.         for (Method m : source.getClass().getMethods()) {  
  217.             if (m.getParameterTypes().length > 0)  
  218.                 continue;  
  219.   
  220.             String name = m.getName();  
  221.             if (name.startsWith("get") && name.length() > 3) {  
  222.                 name = name.substring(3);  
  223.                 getterMap.put(name, m);  
  224.             } else if (name.startsWith("is") && name.length() > 2 && m.getReturnType() == boolean.class) {  
  225.                 name = name.substring(2);  
  226.                 getterMap.put(name, m);  
  227.             }  
  228.   
  229.         }  
  230.   
  231.         for (Method setter : target.getClass().getMethods()) {  
  232.             String name = setter.getName();  
  233.             Type[] paramTypes = setter.getGenericParameterTypes();  
  234.             if (name.startsWith("set") && name.length() > 3 && paramTypes.length == 1) {  
  235.                 name = name.substring(3);  
  236.                 Method getter = getterMap.get(name);  
  237.                 if (getter != null) {  
  238.                     try {  
  239.                         Object value = getter.invoke(source);  
  240.                         if (value != null) {  
  241.                             Type paramType = paramTypes[0];  
  242.                             if (isZteClass(paramType)) {  
  243.                                 try {  
  244.                                     value = copyPropVal(value, ((Class<?>) paramType).newInstance(), copyNull);  
  245.                                 } catch (InstantiationException e) {  
  246.                                 }  
  247.                             } else if (checkCopyAsList(value, paramType)) {  
  248.                                 Type actualType = ((ParameterizedType) paramType).getActualTypeArguments()[0];  
  249.                                 value = makeTargetList((List<?>) value, (Class<?>) actualType, copyNull);  
  250.                             } else if (checkCopyAsMap(value, paramType)) {  
  251.                                 Type keyType = ((ParameterizedType) paramType).getActualTypeArguments()[0];  
  252.                                 Type valType = ((ParameterizedType) paramType).getActualTypeArguments()[1];  
  253.                                 try {  
  254.                                     value = makeTargetMap((Map<??>) value, keyType, valType, copyNull);  
  255.                                 } catch (Exception e) {  
  256.                                     value = null;  
  257.                                 }  
  258.                             }  
  259.   
  260.                             setter.invoke(target, value);  
  261.                         } else if (copyNull) {  
  262.                             setter.invoke(target, value);  
  263.                         }  
  264.                     } catch (IllegalArgumentException e) {  
  265.                         // do nothing  
  266.                     } catch (IllegalAccessException e) {  
  267.                         // do nothing  
  268.                     } catch (InvocationTargetException e) {  
  269.                         // do nothing  
  270.                     }  
  271.                 }  
  272.   
  273.             }  
  274.         }  
  275.   
  276.         return target;  
  277.     }  
  278.   
  279.     public static <T> T copyAs(Object srcBean, Class<T> targetClass) {  
  280.         if (srcBean == null) {  
  281.             return null;  
  282.         }  
  283.   
  284.         T ret;  
  285.         try {  
  286.             ret = targetClass.newInstance();  
  287.         } catch (Exception e) {  
  288.             e.printStackTrace();  
  289.             return null;  
  290.         }  
  291.         return copyPropVal(srcBean, ret);  
  292.     }  
  293.   
  294.     /**  
  295.      * 判断Value是否是List类型,type是泛型List,从而他们可以作为List进行bean Copy  
  296.      *   
  297.      * @param value  
  298.      * @param type  
  299.      * @return  
  300.      */  
  301.     private static boolean checkCopyAsList(Object value, Type type) {  
  302.         if (!(value instanceof List) || !(type instanceof ParameterizedType))  
  303.             return false;  
  304.   
  305.         ParameterizedType paramType = (ParameterizedType) type;  
  306.         if (!(paramType.getRawType() instanceof Class))  
  307.             return false;  
  308.   
  309.         Class<?> rawType = (Class<?>) paramType.getRawType();  
  310.         if (!List.class.isAssignableFrom(rawType) || paramType.getActualTypeArguments().length != 1)  
  311.             return false;  
  312.   
  313.         return true;  
  314.     }  
  315.   
  316.     /**  
  317.      * 判断Value是否是Map类型,type是泛型Map,从而他们可以作为Map进行bean Copy  
  318.      *   
  319.      * @param value  
  320.      * @param type  
  321.      * @return  
  322.      */  
  323.     private static boolean checkCopyAsMap(Object value, Type type) {  
  324.         if (!(value instanceof Map) || !(type instanceof ParameterizedType))  
  325.             return false;  
  326.   
  327.         ParameterizedType paramType = (ParameterizedType) type;  
  328.         if (!(paramType.getRawType() instanceof Class))  
  329.             return false;  
  330.   
  331.         Class<?> rawType = (Class<?>) paramType.getRawType();  
  332.         if (!Map.class.isAssignableFrom(rawType) || paramType.getActualTypeArguments().length != 2)  
  333.             return false;  
  334.   
  335.         return true;  
  336.     }  
  337.   
  338.     @SuppressWarnings("unchecked")  
  339.     public static <T> List<T> makeTargetList(List<?> sourceList, Class<T> targetClzz, boolean copyNull) {  
  340.         if (sourceList == null || targetClzz == null)  
  341.             return null;  
  342.   
  343.         List<T> ret = new ArrayList<T>();  
  344.         for (Object source : sourceList) {  
  345.             if (isZteClass(targetClzz)) {  
  346.                 try {  
  347.                     T target = targetClzz.newInstance();  
  348.                     ret.add(copyPropVal(source, target, copyNull));  
  349.                 } catch (Exception e) {  
  350.                     // do nothing  
  351.                 }  
  352.             } else if (targetClzz.isInstance(source)) {  
  353.                 ret.add((T) source);  
  354.             }  
  355.         }  
  356.         return ret;  
  357.     }  
  358.   
  359.     public static <T> List<T> makeTargetList(List<?> sourceList, Class<T> targetClzz) {  
  360.         return makeTargetList(sourceList, targetClzz, true);  
  361.     }  
  362.   
  363.     public static <T, S> Pagination<T> makePagination(Pagination<S> src, Class<T> targetClzz) {  
  364.         if (src == null)  
  365.             return null;  
  366.   
  367.         Pagination<T> result = new Pagination<T>(src.getCurIndex(), src.getPageSize(), src.getRowsCount());  
  368.         List<T> items = makeTargetList(src.getItems(), targetClzz);  
  369.         result.setItems(items);  
  370.         return result;  
  371.     }  
  372.   
  373.     public static boolean hasText(String textValue) {  
  374.         return textValue != null && !"".equals(textValue);  
  375.     }  
  376.   
  377.     public static boolean hasDate(Date dateValue) {  
  378.         return dateValue != null;  
  379.     }  
  380.   
  381.     public static boolean hasNumeric(Integer numeric) {  
  382.         return numeric != null;  
  383.     }  
  384.   
  385.     /**  
  386.      * 获取字符串的长度,如果有中文,则每个中文字符计为2位  
  387.      *   
  388.      * @param value  
  389.      *            指定的字符串  
  390.      * @return 字符串的长度  
  391.      */  
  392.     public static int length(String value) {  
  393.         int valueLength = 0;  
  394.         String chinese = "[\u0391-\uFFE5]";  
  395.         /* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */  
  396.         for (int i = 0; i < value.length(); i++) {  
  397.             /* 获取一个字符 */  
  398.             String temp = String.valueOf(value.charAt(i));  
  399.             /* 判断是否为中文字符 */  
  400.             if (temp.matches(chinese)) {  
  401.                 /* 中文字符长度为2 */  
  402.                 valueLength += 2;  
  403.             } else {  
  404.                 /* 其他字符长度为1 */  
  405.                 valueLength += 1;  
  406.             }  
  407.         }  
  408.         return valueLength;  
  409.     }  
  410.   
  411. }  
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @date 2013-4-27 上午10:51:14
 * @since 1.0
 */
public class ObjectUtil {
    /**
     * <p>
     * 把原对象的属性值拷贝到目标对象,并返回目标对象.<b>拷贝空值</b>.
     * </p>
     * 
     * @param source
     *            数据来源对象
     * @param target
     *            目标对象
     * @return 目标对象
     */
    public static <T> T copyPropVal(Object source, T target) {
        return copyPropVal(source, target, true);
    }

    /**
     * 把原对象的属性值拷贝到目标对象,并返回目标对象;不处理复合属性;<b>不拷贝空值</b>
     * 
     * @param <T>
     * @param source
     * @param target
     * @return 目标对象
     */
    public static <T> T copyNotNullPropVal(Object source, T target) {
        return copyPropVal(source, target, false);
    }

    private static Object callGetter(Object o, List<Method> getterList) {
        if (getterList == null || o == null)
            return null;

        for (Method m : getterList) {
            if (!m.getReturnType().equals(void.class) && m.getParameterTypes().length == 0) {
                try {
                    return m.invoke(o);
                } catch (Exception e) {
                }
            }
        }
        return null;
    }

    private static void callSetter(Object o, Object val, List<Method> setterList) {
        if (setterList == null || o == null)
            return;

        for (Method m : setterList) {
            if (m.getReturnType().equals(void.class) && m.getParameterTypes().length == 1) {
                try {
                    m.invoke(o, val);
                    return;
                } catch (Exception e) {
                }
            }
        }
    }

    /**
     * 见prepareToSave,空值默认<b>不</b>覆盖
     * 
     * @param savingEntity
     *            要保存到数据库的实体对象
     * @param valueEntity
     *            数值实体
     * @param userId
     *            当前用户ID
     * @return 处理以后的参数savingEntity
     */
    public static <T> T prepareToSave(T savingEntity, Object valueEntity, String userId) {
        return prepareToSave(savingEntity, valueEntity, userId, false);
    }

    /**
     * 在保存savingEntity实体之前,完成对savingEntity字段值的设置操作,具体如下:<br>
     * 1)设置savingEntity的通用字段getDisabled(isDisabled), getCreateTime,
     * getCreatedBy,setCreateTime,setCreateBy,setUpdateTime,setUpdateBy 2)拷贝
     * 数值实体valueEntity 所有属性值到savingEntity相应属性<br>
     * 本方法返回待保存的实体
     * 
     * @param <T>
     * @param savingEntity
     *            要保存到数据库的实体对象
     * @param valueEntity
     *            数值实体
     * @param userId
     *            当前用户ID
     * @param copyNull
     *            是否拷贝空值
     * @return 处理以后的参数savingEntity
     */
    public static <T> T prepareToSave(T savingEntity, Object valueEntity, String userId, boolean copyNull) {
        if (savingEntity == null)
            return savingEntity;

        HashMap<String, List<Method>> methodMap = new HashMap<String, List<Method>>();
        for (Method m : savingEntity.getClass().getMethods()) {
            List<Method> list = methodMap.get(m.getName());
            if (list == null) {
                list = new ArrayList<Method>();
                methodMap.put(m.getName(), list);
            }
            list.add(m);
        }

        Object createTime = callGetter(savingEntity, methodMap.get("getCreateTime"));
        Object createBy = callGetter(savingEntity, methodMap.get("getCreateBy"));

        copyPropVal(valueEntity, savingEntity, copyNull);

        Date now = new Date();
        if (createTime == null)
            createTime = now;
        if (createBy == null)
            createBy = userId;

        // ~~exam or ERP~~
        Object creationDate = callGetter(savingEntity, methodMap.get("getCreationDate"));
        Object createdBy = callGetter(savingEntity, methodMap.get("getCreatedBy"));
        if (createdBy == null)
            createdBy = userId;
        if (creationDate == null)
            creationDate = now;
        // ~~exam or ERP~~

        Object disabled = callGetter(savingEntity, methodMap.get("getDisabled"));
        if (disabled == null)
            disabled = callGetter(savingEntity, methodMap.get("isDisabled"));
        if (disabled == null)
            callSetter(savingEntity, false, methodMap.get("setDisabled"));

        callSetter(savingEntity, createBy, methodMap.get("setCreateBy"));
        callSetter(savingEntity, createTime, methodMap.get("setCreateTime"));
        callSetter(savingEntity, now, methodMap.get("setUpdateTime"));
        callSetter(savingEntity, userId, methodMap.get("setUpdateBy"));

        // ~~exam or ERP~~
        callSetter(savingEntity, createdBy, methodMap.get("setCreatedBy"));
        callSetter(savingEntity, creationDate, methodMap.get("setCreationDate"));
        callSetter(savingEntity, now, methodMap.get("setLastUpdateDate"));
        callSetter(savingEntity, userId, methodMap.get("setLastUpdatedBy"));
        callSetter(savingEntity, userId, methodMap.get("setLastUpdateLogin"));
        // ~~exam or ERP~~
        return savingEntity;
    }

    private static boolean isZteClass(Type type) {
        if (!(type instanceof Class))
            return false;
        DataObjectDescriptor annotation = ((Class<?>) type).getAnnotation(DataObjectDescriptor.class);
        return annotation != null;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private static Map<?, ?> makeTargetMap(Map<?, ?> source, Type keyType, Type valType, boolean copyNull)
            throws Exception {
        if (!(keyType instanceof Class))
            throw new UnsupportedOperationException("makeTargetMap " + keyType);

        Class<?> keyClzz = (Class<?>) keyType;

        Map result = new HashMap();
        for (Object k : source.keySet()) {
            Object srcVal = source.get(k);
            Object value = srcVal;
            Object key = k;
            if (isZteClass(keyClzz))
                key = copyNotNullPropVal(k, keyClzz.newInstance());

            if (isZteClass(valType)) {
                value = copyPropVal(srcVal, ((Class<?>) valType).newInstance(), copyNull);
            } else if (checkCopyAsList(srcVal, valType)) {
                Type actualType = ((ParameterizedType) valType).getActualTypeArguments()[0];
                value = makeTargetList((List<?>) srcVal, (Class<?>) actualType, copyNull);
            } else if (checkCopyAsMap(srcVal, valType)) {
                ParameterizedType prmType = (ParameterizedType) valType;
                Type subKeyType = prmType.getActualTypeArguments()[0];
                Type subValType = prmType.getActualTypeArguments()[1];
                value = makeTargetMap((Map<?, ?>) srcVal, subKeyType, subValType, copyNull);
            }
            result.put(key, value);
        }
        return result;
    }

    /**
     * 把原对象的属性值拷贝到目标对象,并返回目标对象;不处理复合属性,可控制是否拷贝空值
     * 
     * @param <T>
     * @param source
     * @param target
     * @param copyNull
     *            是否拷贝空值
     * @return 目标对象
     */
    public static <T> T copyPropVal(Object source, T target, boolean copyNull) {
        if (source == null || target == null)
            return target;

        Map<String, Method> getterMap = new HashMap<String, Method>();
        for (Method m : source.getClass().getMethods()) {
            if (m.getParameterTypes().length > 0)
                continue;

            String name = m.getName();
            if (name.startsWith("get") && name.length() > 3) {
                name = name.substring(3);
                getterMap.put(name, m);
            } else if (name.startsWith("is") && name.length() > 2 && m.getReturnType() == boolean.class) {
                name = name.substring(2);
                getterMap.put(name, m);
            }

        }

        for (Method setter : target.getClass().getMethods()) {
            String name = setter.getName();
            Type[] paramTypes = setter.getGenericParameterTypes();
            if (name.startsWith("set") && name.length() > 3 && paramTypes.length == 1) {
                name = name.substring(3);
                Method getter = getterMap.get(name);
                if (getter != null) {
                    try {
                        Object value = getter.invoke(source);
                        if (value != null) {
                            Type paramType = paramTypes[0];
                            if (isZteClass(paramType)) {
                                try {
                                    value = copyPropVal(value, ((Class<?>) paramType).newInstance(), copyNull);
                                } catch (InstantiationException e) {
                                }
                            } else if (checkCopyAsList(value, paramType)) {
                                Type actualType = ((ParameterizedType) paramType).getActualTypeArguments()[0];
                                value = makeTargetList((List<?>) value, (Class<?>) actualType, copyNull);
                            } else if (checkCopyAsMap(value, paramType)) {
                                Type keyType = ((ParameterizedType) paramType).getActualTypeArguments()[0];
                                Type valType = ((ParameterizedType) paramType).getActualTypeArguments()[1];
                                try {
                                    value = makeTargetMap((Map<?, ?>) value, keyType, valType, copyNull);
                                } catch (Exception e) {
                                    value = null;
                                }
                            }

                            setter.invoke(target, value);
                        } else if (copyNull) {
                            setter.invoke(target, value);
                        }
                    } catch (IllegalArgumentException e) {
                        // do nothing
                    } catch (IllegalAccessException e) {
                        // do nothing
                    } catch (InvocationTargetException e) {
                        // do nothing
                    }
                }

            }
        }

        return target;
    }

    public static <T> T copyAs(Object srcBean, Class<T> targetClass) {
        if (srcBean == null) {
            return null;
        }

        T ret;
        try {
            ret = targetClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return copyPropVal(srcBean, ret);
    }

    /**
     * 判断Value是否是List类型,type是泛型List,从而他们可以作为List进行bean Copy
     * 
     * @param value
     * @param type
     * @return
     */
    private static boolean checkCopyAsList(Object value, Type type) {
        if (!(value instanceof List) || !(type instanceof ParameterizedType))
            return false;

        ParameterizedType paramType = (ParameterizedType) type;
        if (!(paramType.getRawType() instanceof Class))
            return false;

        Class<?> rawType = (Class<?>) paramType.getRawType();
        if (!List.class.isAssignableFrom(rawType) || paramType.getActualTypeArguments().length != 1)
            return false;

        return true;
    }

    /**
     * 判断Value是否是Map类型,type是泛型Map,从而他们可以作为Map进行bean Copy
     * 
     * @param value
     * @param type
     * @return
     */
    private static boolean checkCopyAsMap(Object value, Type type) {
        if (!(value instanceof Map) || !(type instanceof ParameterizedType))
            return false;

        ParameterizedType paramType = (ParameterizedType) type;
        if (!(paramType.getRawType() instanceof Class))
            return false;

        Class<?> rawType = (Class<?>) paramType.getRawType();
        if (!Map.class.isAssignableFrom(rawType) || paramType.getActualTypeArguments().length != 2)
            return false;

        return true;
    }

    @SuppressWarnings("unchecked")
    public static <T> List<T> makeTargetList(List<?> sourceList, Class<T> targetClzz, boolean copyNull) {
        if (sourceList == null || targetClzz == null)
            return null;

        List<T> ret = new ArrayList<T>();
        for (Object source : sourceList) {
            if (isZteClass(targetClzz)) {
                try {
                    T target = targetClzz.newInstance();
                    ret.add(copyPropVal(source, target, copyNull));
                } catch (Exception e) {
                    // do nothing
                }
            } else if (targetClzz.isInstance(source)) {
                ret.add((T) source);
            }
        }
        return ret;
    }

    public static <T> List<T> makeTargetList(List<?> sourceList, Class<T> targetClzz) {
        return makeTargetList(sourceList, targetClzz, true);
    }

    public static <T, S> Pagination<T> makePagination(Pagination<S> src, Class<T> targetClzz) {
        if (src == null)
            return null;

        Pagination<T> result = new Pagination<T>(src.getCurIndex(), src.getPageSize(), src.getRowsCount());
        List<T> items = makeTargetList(src.getItems(), targetClzz);
        result.setItems(items);
        return result;
    }

    public static boolean hasText(String textValue) {
        return textValue != null && !"".equals(textValue);
    }

    public static boolean hasDate(Date dateValue) {
        return dateValue != null;
    }

    public static boolean hasNumeric(Integer numeric) {
        return numeric != null;
    }

    /**
     * 获取字符串的长度,如果有中文,则每个中文字符计为2位
     * 
     * @param value
     *            指定的字符串
     * @return 字符串的长度
     */
    public static int length(String value) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */
        for (int i = 0; i < value.length(); i++) {
            /* 获取一个字符 */
            String temp = String.valueOf(value.charAt(i));
            /* 判断是否为中文字符 */
            if (temp.matches(chinese)) {
                /* 中文字符长度为2 */
                valueLength += 2;
            } else {
                /* 其他字符长度为1 */
                valueLength += 1;
            }
        }
        return valueLength;
    }

}

DataObjectDescriptor.java

  1. import java.lang.annotation.Documented;  
  2. import java.lang.annotation.Retention;  
  3. import java.lang.annotation.RetentionPolicy;  
  4. import java.lang.annotation.Target;  
  5.   
  6. @Retention(RetentionPolicy.RUNTIME)  
  7. @Target({ java.lang.annotation.ElementType.TYPE })  
  8. @Documented  
  9. public @interface DataObjectDescriptor {  
  10.     public abstract String value();  
  11. }  
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ java.lang.annotation.ElementType.TYPE })
@Documented
public @interface DataObjectDescriptor {
    public abstract String value();
}

DaoException.java

  1. import org.springframework.core.NestedRuntimeException;  
  2.   
  3. /**  
  4.  * @author   
  5.  */  
  6. public class DaoException extends NestedRuntimeException {  
  7.   
  8.     private static final long serialVersionUID = 1L;  
  9.   
  10.     public DaoException(String msg) {  
  11.         super(msg);  
  12.     }  
  13.   
  14.     public DaoException(String msg, Throwable obj) {  
  15.         super(msg, obj);  
  16.     }  
  17. }  
import org.springframework.core.NestedRuntimeException;

/**
 * @author 
 */
public class DaoException extends NestedRuntimeException {

    private static final long serialVersionUID = 1L;

    public DaoException(String msg) {
        super(msg);
    }

    public DaoException(String msg, Throwable obj) {
        super(msg, obj);
    }
}


SessionTimeoutException.java

  1. import org.springframework.core.NestedRuntimeException;  
  2.   
  3. public class SessionTimeoutException extends NestedRuntimeException {  
  4.     private static final long serialVersionUID = 1L;  
  5.   
  6.     public SessionTimeoutException(String msg) {  
  7.         super(msg);  
  8.     }  
  9.   
  10.     public SessionTimeoutException(String msg, Throwable obj) {  
  11.         super(msg, obj);  
  12.     }  
  13.   
  14. }  
import org.springframework.core.NestedRuntimeException;

public class SessionTimeoutException extends NestedRuntimeException {
    private static final long serialVersionUID = 1L;

    public SessionTimeoutException(String msg) {
        super(msg);
    }

    public SessionTimeoutException(String msg, Throwable obj) {
        super(msg, obj);
    }

}


PagerFactory.java

  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3.   
  4. public class PagerFactory {  
  5.     public static <T> Pagination<T> createEmpty() {  
  6.         return create(1, 10);  
  7.     }  
  8.   
  9.     public static <T> Pagination<T> create(Number pageIndex, Number pageSize) {  
  10.         return create(pageIndex, pageSize, 0, new ArrayList<T>(0));  
  11.     }  
  12.   
  13.     public static <T> Pagination<T> create(Number pageIndex, Number pageSize, Number rowsCount) {  
  14.         return create(pageIndex, pageSize, rowsCount, new ArrayList<T>(0));  
  15.     }  
  16.   
  17.     public static <T> Pagination<T> create(Number pageIndex, Number pageSize, Number rowsCount, List<T> data) {  
  18.         Pagination<T> p = new Pagination<T>(pageIndex.longValue(), pageSize.longValue(), rowsCount.longValue());  
  19.         if (data == null) {  
  20.             data = new ArrayList<T>(0);  
  21.         }  
  22.         p.setItems(data);  
  23.         return p;  
  24.     }  
  25.   
  26.     public static <T> List<T> getPaginList(List<T> allList, int pageIndex, int pageSize) {  
  27.         List<T> result = new ArrayList<T>();  
  28.         int start = pageIndex < 2 ? 0 : ((pageIndex - 1) * pageSize);  
  29.         int end = start + pageSize > allList.size() ? allList.size() : start + pageSize;  
  30.         for (int i = start; i < end; i++) {  
  31.             result.add(allList.get(i));  
  32.         }  
  33.         return result;  
  34.     }  
  35. }  
import java.util.ArrayList;
import java.util.List;

public class PagerFactory {
    public static <T> Pagination<T> createEmpty() {
        return create(1, 10);
    }

    public static <T> Pagination<T> create(Number pageIndex, Number pageSize) {
        return create(pageIndex, pageSize, 0, new ArrayList<T>(0));
    }

    public static <T> Pagination<T> create(Number pageIndex, Number pageSize, Number rowsCount) {
        return create(pageIndex, pageSize, rowsCount, new ArrayList<T>(0));
    }

    public static <T> Pagination<T> create(Number pageIndex, Number pageSize, Number rowsCount, List<T> data) {
        Pagination<T> p = new Pagination<T>(pageIndex.longValue(), pageSize.longValue(), rowsCount.longValue());
        if (data == null) {
            data = new ArrayList<T>(0);
        }
        p.setItems(data);
        return p;
    }

    public static <T> List<T> getPaginList(List<T> allList, int pageIndex, int pageSize) {
        List<T> result = new ArrayList<T>();
        int start = pageIndex < 2 ? 0 : ((pageIndex - 1) * pageSize);
        int end = start + pageSize > allList.size() ? allList.size() : start + pageSize;
        for (int i = start; i < end; i++) {
            result.add(allList.get(i));
        }
        return result;
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值