打包JPA动态查询(CriteriaQuery) eq、ge、gt

封装JPA动态查询(CriteriaQuery)

 

JPA动态查询(CriteriaQuery)封装的一段代码:

  1. package com.platform.framework.dao.jpa;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.ArrayList;  
  5. import java.util.Collection;  
  6. import java.util.Date;  
  7. import java.util.HashMap;  
  8. import java.util.Iterator;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11.   
  12. import javax.persistence.EntityManager;  
  13. import javax.persistence.criteria.CriteriaBuilder;  
  14. import javax.persistence.criteria.CriteriaBuilder.In;  
  15. import javax.persistence.criteria.CriteriaQuery;  
  16. import javax.persistence.criteria.Order;  
  17. import javax.persistence.criteria.Predicate;  
  18. import javax.persistence.criteria.Root;  
  19.   
  20. import org.apache.log4j.Logger;  
  21.   
  22. /** 
  23.  * Query基类<br> 
  24.  *  
  25.  * @describe:封装JPA CriteriaBuilder查询条件 
  26.  * @author:lry 
  27.  * @since:2014-05-23 
  28.  */  
  29. @SuppressWarnings({ “unused”“unchecked”“rawtypes”“null”“hiding” })  
  30. public class Query implements Serializable {  
  31.   
  32.     private static final long serialVersionUID = 5064932771068929342L;  
  33.   
  34.     private static Logger log = Logger.getLogger(Query.class);  
  35.   
  36.     private EntityManager entityManager;  
  37.   
  38.     /** 要查询的模型对象 */  
  39.     private Class clazz;  
  40.   
  41.     /** 查询条件列表 */  
  42.     private Root from;  
  43.   
  44.     private List<Predicate> predicates;  
  45.   
  46.     private CriteriaQuery criteriaQuery;  
  47.   
  48.     private CriteriaBuilder criteriaBuilder;  
  49.   
  50.     /** 排序方式列表 */  
  51.     private List<Order> orders;  
  52.   
  53.     /** 关联模式 */  
  54.     private Map<String, Query> subQuery;  
  55.   
  56.     private Map<String, Query> linkQuery;  
  57.   
  58.     private String projection;  
  59.   
  60.     /** 或条件 */  
  61.     private List<Query> orQuery;  
  62.   
  63.     private String groupBy;  
  64.   
  65.     private Query() {  
  66.     }  
  67.   
  68.     private Query(Class clazz, EntityManager entityManager) {  
  69.         this.clazz = clazz;  
  70.         this.entityManager = entityManager;  
  71.         this.criteriaBuilder = this.entityManager.getCriteriaBuilder();  
  72.         this.criteriaQuery = criteriaBuilder.createQuery(this.clazz);  
  73.         this.from = criteriaQuery.from(this.clazz);  
  74.         this.predicates = new ArrayList();  
  75.         this.orders = new ArrayList();  
  76.     }  
  77.   
  78.     /** 通过类创建查询条件 */  
  79.     public static Query forClass(Class clazz, EntityManager entityManager) {  
  80.         return new Query(clazz, entityManager);  
  81.     }  
  82.   
  83.     /** 增加子查询 */  
  84.     private void addSubQuery(String propertyName, Query query) {  
  85.         if (this.subQuery == null)  
  86.             this.subQuery = new HashMap();  
  87.   
  88.         if (query.projection == null)  
  89.             throw new RuntimeException(“子查询字段未设置”);  
  90.   
  91.         this.subQuery.put(propertyName, query);  
  92.     }  
  93.   
  94.     private void addSubQuery(Query query) {  
  95.         addSubQuery(query.projection, query);  
  96.     }  
  97.   
  98.     /** 增关联查询 */  
  99.     public void addLinkQuery(String propertyName, Query query) {  
  100.         if (this.linkQuery == null)  
  101.             this.linkQuery = new HashMap();  
  102.   
  103.         this.linkQuery.put(propertyName, query);  
  104.     }  
  105.   
  106.     /** 相等 */  
  107.     public void eq(String propertyName, Object value) {  
  108.         if (isNullOrEmpty(value))  
  109.             return;  
  110.         this.predicates.add(criteriaBuilder.equal(from.get(propertyName), value));  
  111.     }  
  112.   
  113.     private boolean isNullOrEmpty(Object value) {  
  114.         if (value instanceof String) {  
  115.             return value == null || “”.equals(value);  
  116.         }  
  117.         return value == null;  
  118.     }  
  119.   
  120.     public void or(List<String> propertyName, Object value) {  
  121.         if (isNullOrEmpty(value))  
  122.             return;  
  123.         if ((propertyName == null) || (propertyName.size() == 0))  
  124.             return;  
  125.         Predicate predicate = criteriaBuilder.or(criteriaBuilder.equal(from.get(propertyName.get(0)), value));  
  126.         for (int i = 1; i < propertyName.size(); ++i)  
  127.             predicate = criteriaBuilder.or(predicate, criteriaBuilder.equal(from.get(propertyName.get(i)), value));  
  128.         this.predicates.add(predicate);  
  129.     }  
  130.   
  131.     public void orLike(List<String> propertyName, String value) {  
  132.         if (isNullOrEmpty(value) || (propertyName.size() == 0))  
  133.             return;  
  134.         if (value.indexOf(“%”) < 0)  
  135.             value = ”%” + value + “%”;  
  136.         Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(from.get(propertyName.get(0)), value.toString()));  
  137.         for (int i = 1; i < propertyName.size(); ++i)  
  138.             predicate = criteriaBuilder.or(predicate, criteriaBuilder.like(from.get(propertyName.get(i)), value));  
  139.         this.predicates.add(predicate);  
  140.     }  
  141.   
  142.     /** 空 */  
  143.     public void isNull(String propertyName) {  
  144.         this.predicates.add(criteriaBuilder.isNull(from.get(propertyName)));  
  145.     }  
  146.   
  147.     /** 非空 */  
  148.     public void isNotNull(String propertyName) {  
  149.         this.predicates.add(criteriaBuilder.isNotNull(from.get(propertyName)));  
  150.     }  
  151.   
  152.     /** 不相等 */  
  153.     public void notEq(String propertyName, Object value) {  
  154.         if (isNullOrEmpty(value)) {  
  155.             return;  
  156.         }  
  157.         this.predicates.add(criteriaBuilder.notEqual(from.get(propertyName), value));  
  158.     }  
  159.   
  160.     /** 
  161.      * not in 
  162.      *  
  163.      * @param propertyName 
  164.      *            属性名称 
  165.      * @param value 
  166.      *            值集合 
  167.      */  
  168.     public void notIn(String propertyName, Collection value) {  
  169.         if ((value == null) || (value.size() == 0)) {  
  170.             return;  
  171.         }  
  172.         Iterator iterator = value.iterator();  
  173.         In in = criteriaBuilder.in(from.get(propertyName));  
  174.         while (iterator.hasNext()) {  
  175.             in.value(iterator.next());  
  176.         }  
  177.         this.predicates.add(criteriaBuilder.not(in));  
  178.     }  
  179.   
  180.     /** 
  181.      * 模糊匹配 
  182.      *  
  183.      * @param propertyName 
  184.      *            属性名称 
  185.      * @param value 
  186.      *            属性值 
  187.      */  
  188.     public void like(String propertyName, String value) {  
  189.         if (isNullOrEmpty(value))  
  190.             return;  
  191.         if (value.indexOf(“%”) < 0)  
  192.             value = ”%” + value + “%”;  
  193.         this.predicates.add(criteriaBuilder.like(from.get(propertyName), value));  
  194.     }  
  195.   
  196.     /** 
  197.      * 时间区间查询 
  198.      *  
  199.      * @param propertyName 
  200.      *            属性名称 
  201.      * @param lo 
  202.      *            属性起始值 
  203.      * @param go 
  204.      *            属性结束值 
  205.      */  
  206.     public void between(String propertyName, Date lo, Date go) {  
  207.         if (!isNullOrEmpty(lo) && !isNullOrEmpty(go)) {  
  208.             this.predicates.add(criteriaBuilder.between(from.get(propertyName), lo, go));  
  209.         }  
  210.   
  211.         // if (!isNullOrEmpty(lo) && !isNullOrEmpty(go)) {  
  212.         // this.predicates.add(criteriaBuilder.lessThan(from.get(propertyName),  
  213.         // new DateTime(lo).toString()));  
  214.         // }  
  215.         // if (!isNullOrEmpty(go)) {  
  216.         // this.predicates.add(criteriaBuilder.greaterThan(from.get(propertyName),  
  217.         // new DateTime(go).toString()));  
  218.         // }  
  219.   
  220.     }  
  221.   
  222.     public void between(String propertyName, Number lo, Number go) {  
  223.         if (!(isNullOrEmpty(lo)))  
  224.             ge(propertyName, lo);  
  225.   
  226.         if (!(isNullOrEmpty(go)))  
  227.             le(propertyName, go);  
  228.     }  
  229.   
  230.     /** 
  231.      * 小于等于 
  232.      *  
  233.      * @param propertyName 
  234.      *            属性名称 
  235.      * @param value 
  236.      *            属性值 
  237.      */  
  238.     public void le(String propertyName, Number value) {  
  239.         if (isNullOrEmpty(value)) {  
  240.             return;  
  241.         }  
  242.         this.predicates.add(criteriaBuilder.le(from.get(propertyName), value));  
  243.     }  
  244.   
  245.     /** 
  246.      * 小于 
  247.      *  
  248.      * @param propertyName 
  249.      *            属性名称 
  250.      * @param value 
  251.      *            属性值 
  252.      */  
  253.     public void lt(String propertyName, Number value) {  
  254.         if (isNullOrEmpty(value)) {  
  255.             return;  
  256.         }  
  257.         this.predicates.add(criteriaBuilder.lt(from.get(propertyName), value));  
  258.     }  
  259.   
  260.     /** 
  261.      * 大于等于 
  262.      *  
  263.      * @param propertyName 
  264.      *            属性名称 
  265.      * @param value 
  266.      *            属性值 
  267.      */  
  268.     public void ge(String propertyName, Number value) {  
  269.         if (isNullOrEmpty(value)) {  
  270.             return;  
  271.         }  
  272.         this.predicates.add(criteriaBuilder.ge(from.get(propertyName), value));  
  273.     }  
  274.   
  275.     /** 
  276.      * 大于 
  277.      *  
  278.      * @param propertyName 
  279.      *            属性名称 
  280.      * @param value 
  281.      *            属性值 
  282.      */  
  283.     public void gt(String propertyName, Number value) {  
  284.         if (isNullOrEmpty(value)) {  
  285.             return;  
  286.         }  
  287.         this.predicates.add(criteriaBuilder.gt(from.get(propertyName), value));  
  288.     }  
  289.   
  290.     /** 
  291.      * in 
  292.      *  
  293.      * @param propertyName 
  294.      *            属性名称 
  295.      * @param value 
  296.      *            值集合 
  297.      */  
  298.     public void in(String propertyName, Collection value) {  
  299.         if ((value == null) || (value.size() == 0)) {  
  300.             return;  
  301.         }  
  302.         Iterator iterator = value.iterator();  
  303.         In in = criteriaBuilder.in(from.get(propertyName));  
  304.         while (iterator.hasNext()) {  
  305.             in.value(iterator.next());  
  306.         }  
  307.         this.predicates.add(in);  
  308.     }  
  309.   
  310.     /** 直接添加JPA内部的查询条件,用于应付一些复杂查询的情况,例如或 */  
  311.     public void addCriterions(Predicate predicate) {  
  312.         this.predicates.add(predicate);  
  313.     }  
  314.   
  315.     /** 
  316.      * 创建查询条件 
  317.      *  
  318.      * @return JPA离线查询 
  319.      */  
  320.     public CriteriaQuery newCriteriaQuery() {  
  321.         criteriaQuery.where(predicates.toArray(new Predicate[0]));  
  322.         if (!isNullOrEmpty(groupBy)) {  
  323.             criteriaQuery.groupBy(from.get(groupBy));  
  324.         }  
  325.         if (this.orders != null) {  
  326.             criteriaQuery.orderBy(orders);  
  327.         }  
  328.         addLinkCondition(this);  
  329.         return criteriaQuery;  
  330.     }  
  331.   
  332.     private void addLinkCondition(Query query) {  
  333.   
  334.         Map subQuery = query.linkQuery;  
  335.         if (subQuery == null)  
  336.             return;  
  337.   
  338.         for (Iterator queryIterator = subQuery.keySet().iterator(); queryIterator.hasNext();) {  
  339.             String key = (String) queryIterator.next();  
  340.             Query sub = (Query) subQuery.get(key);  
  341.             from.join(key);  
  342.             criteriaQuery.where(sub.predicates.toArray(new Predicate[0]));  
  343.             addLinkCondition(sub);  
  344.         }  
  345.     }  
  346.   
  347.     public void addOrder(String propertyName, String order) {  
  348.         if (order == null || propertyName == null)  
  349.             return;  
  350.   
  351.         if (this.orders == null)  
  352.             this.orders = new ArrayList();  
  353.   
  354.         if (order.equalsIgnoreCase(“asc”))  
  355.             this.orders.add(criteriaBuilder.asc(from.get(propertyName)));  
  356.         else if (order.equalsIgnoreCase(“desc”))  
  357.             this.orders.add(criteriaBuilder.desc(from.get(propertyName)));  
  358.     }  
  359.   
  360.     public void setOrder(String propertyName, String order) {  
  361.         this.orders = null;  
  362.         addOrder(propertyName, order);  
  363.     }  
  364.   
  365.     public Class getModleClass() {  
  366.         return this.clazz;  
  367.     }  
  368.   
  369.     public String getProjection() {  
  370.         return this.projection;  
  371.     }  
  372.   
  373.     public void setProjection(String projection) {  
  374.         this.projection = projection;  
  375.     }  
  376.   
  377.     public Class getClazz() {  
  378.         return this.clazz;  
  379.     }  
  380.   
  381.     public List<Order> getOrders() {  
  382.         return orders;  
  383.     }  
  384.   
  385.     public void setOrders(List<Order> orders) {  
  386.         this.orders = orders;  
  387.     }  
  388.   
  389.     public EntityManager getEntityManager() {  
  390.         return this.entityManager;  
  391.     }  
  392.   
  393.     public void setEntityManager(EntityManager em) {  
  394.         this.entityManager = em;  
  395.     }  
  396.   
  397.     public Root getFrom() {  
  398.         return from;  
  399.     }  
  400.   
  401.     public List<Predicate> getPredicates() {  
  402.         return predicates;  
  403.     }  
  404.   
  405.     public void setPredicates(List<Predicate> predicates) {  
  406.         this.predicates = predicates;  
  407.     }  
  408.   
  409.     public CriteriaQuery getCriteriaQuery() {  
  410.         return criteriaQuery;  
  411.     }  
  412.   
  413.     public CriteriaBuilder getCriteriaBuilder() {  
  414.         return criteriaBuilder;  
  415.     }  
  416.   
  417.     public void setFetchModes(List<String> fetchField, List<String> fetchMode) {  
  418.   
  419.     }  
  420.   
  421.     public String getGroupBy() {  
  422.         return groupBy;  
  423.     }  
  424.   
  425.     public void setGroupBy(String groupBy) {  
  426.         this.groupBy = groupBy;  
  427.     }  
  428.   
  429. }  
package com.platform.framework.dao.jpa;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.log4j.Logger;

/**
 * Query基类<br>
 * 
 * @describe:封装JPA CriteriaBuilder查询条件
 * @author:lry
 * @since:2014-05-23
 */
@SuppressWarnings({ "unused", "unchecked", "rawtypes", "null", "hiding" })
public class Query implements Serializable {

    private static final long serialVersionUID = 5064932771068929342L;

    private static Logger log = Logger.getLogger(Query.class);

    private EntityManager entityManager;

    /** 要查询的模型对象 */
    private Class clazz;

    /** 查询条件列表 */
    private Root from;

    private List<Predicate> predicates;

    private CriteriaQuery criteriaQuery;

    private CriteriaBuilder criteriaBuilder;

    /** 排序方式列表 */
    private List<Order> orders;

    /** 关联模式 */
    private Map<String, Query> subQuery;

    private Map<String, Query> linkQuery;

    private String projection;

    /** 或条件 */
    private List<Query> orQuery;

    private String groupBy;

    private Query() {
    }

    private Query(Class clazz, EntityManager entityManager) {
        this.clazz = clazz;
        this.entityManager = entityManager;
        this.criteriaBuilder = this.entityManager.getCriteriaBuilder();
        this.criteriaQuery = criteriaBuilder.createQuery(this.clazz);
        this.from = criteriaQuery.from(this.clazz);
        this.predicates = new ArrayList();
        this.orders = new ArrayList();
    }

    /** 通过类创建查询条件 */
    public static Query forClass(Class clazz, EntityManager entityManager) {
        return new Query(clazz, entityManager);
    }

    /** 增加子查询 */
    private void addSubQuery(String propertyName, Query query) {
        if (this.subQuery == null)
            this.subQuery = new HashMap();

        if (query.projection == null)
            throw new RuntimeException("子查询字段未设置");

        this.subQuery.put(propertyName, query);
    }

    private void addSubQuery(Query query) {
        addSubQuery(query.projection, query);
    }

    /** 增关联查询 */
    public void addLinkQuery(String propertyName, Query query) {
        if (this.linkQuery == null)
            this.linkQuery = new HashMap();

        this.linkQuery.put(propertyName, query);
    }

    /** 相等 */
    public void eq(String propertyName, Object value) {
        if (isNullOrEmpty(value))
            return;
        this.predicates.add(criteriaBuilder.equal(from.get(propertyName), value));
    }

    private boolean isNullOrEmpty(Object value) {
        if (value instanceof String) {
            return value == null || "".equals(value);
        }
        return value == null;
    }

    public void or(List<String> propertyName, Object value) {
        if (isNullOrEmpty(value))
            return;
        if ((propertyName == null) || (propertyName.size() == 0))
            return;
        Predicate predicate = criteriaBuilder.or(criteriaBuilder.equal(from.get(propertyName.get(0)), value));
        for (int i = 1; i < propertyName.size(); ++i)
            predicate = criteriaBuilder.or(predicate, criteriaBuilder.equal(from.get(propertyName.get(i)), value));
        this.predicates.add(predicate);
    }

    public void orLike(List<String> propertyName, String value) {
        if (isNullOrEmpty(value) || (propertyName.size() == 0))
            return;
        if (value.indexOf("%") < 0)
            value = "%" + value + "%";
        Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(from.get(propertyName.get(0)), value.toString()));
        for (int i = 1; i < propertyName.size(); ++i)
            predicate = criteriaBuilder.or(predicate, criteriaBuilder.like(from.get(propertyName.get(i)), value));
        this.predicates.add(predicate);
    }

    /** 空 */
    public void isNull(String propertyName) {
        this.predicates.add(criteriaBuilder.isNull(from.get(propertyName)));
    }

    /** 非空 */
    public void isNotNull(String propertyName) {
        this.predicates.add(criteriaBuilder.isNotNull(from.get(propertyName)));
    }

    /** 不相等 */
    public void notEq(String propertyName, Object value) {
        if (isNullOrEmpty(value)) {
            return;
        }
        this.predicates.add(criteriaBuilder.notEqual(from.get(propertyName), value));
    }

    /**
     * not in
     * 
     * @param propertyName
     *            属性名称
     * @param value
     *            值集合
     */
    public void notIn(String propertyName, Collection value) {
        if ((value == null) || (value.size() == 0)) {
            return;
        }
        Iterator iterator = value.iterator();
        In in = criteriaBuilder.in(from.get(propertyName));
        while (iterator.hasNext()) {
            in.value(iterator.next());
        }
        this.predicates.add(criteriaBuilder.not(in));
    }

    /**
     * 模糊匹配
     * 
     * @param propertyName
     *            属性名称
     * @param value
     *            属性值
     */
    public void like(String propertyName, String value) {
        if (isNullOrEmpty(value))
            return;
        if (value.indexOf("%") < 0)
            value = "%" + value + "%";
        this.predicates.add(criteriaBuilder.like(from.get(propertyName), value));
    }

    /**
     * 时间区间查询
     * 
     * @param propertyName
     *            属性名称
     * @param lo
     *            属性起始值
     * @param go
     *            属性结束值
     */
    public void between(String propertyName, Date lo, Date go) {
        if (!isNullOrEmpty(lo) && !isNullOrEmpty(go)) {
            this.predicates.add(criteriaBuilder.between(from.get(propertyName), lo, go));
        }

        // if (!isNullOrEmpty(lo) && !isNullOrEmpty(go)) {
        // this.predicates.add(criteriaBuilder.lessThan(from.get(propertyName),
        // new DateTime(lo).toString()));
        // }
        // if (!isNullOrEmpty(go)) {
        // this.predicates.add(criteriaBuilder.greaterThan(from.get(propertyName),
        // new DateTime(go).toString()));
        // }

    }

    public void between(String propertyName, Number lo, Number go) {
        if (!(isNullOrEmpty(lo)))
            ge(propertyName, lo);

        if (!(isNullOrEmpty(go)))
            le(propertyName, go);
    }

    /**
     * 小于等于
     * 
     * @param propertyName
     *            属性名称
     * @param value
     *            属性值
     */
    public void le(String propertyName, Number value) {
        if (isNullOrEmpty(value)) {
            return;
        }
        this.predicates.add(criteriaBuilder.le(from.get(propertyName), value));
    }

    /**
     * 小于
     * 
     * @param propertyName
     *            属性名称
     * @param value
     *            属性值
     */
    public void lt(String propertyName, Number value) {
        if (isNullOrEmpty(value)) {
            return;
        }
        this.predicates.add(criteriaBuilder.lt(from.get(propertyName), value));
    }

    /**
     * 大于等于
     * 
     * @param propertyName
     *            属性名称
     * @param value
     *            属性值
     */
    public void ge(String propertyName, Number value) {
        if (isNullOrEmpty(value)) {
            return;
        }
        this.predicates.add(criteriaBuilder.ge(from.get(propertyName), value));
    }

    /**
     * 大于
     * 
     * @param propertyName
     *            属性名称
     * @param value
     *            属性值
     */
    public void gt(String propertyName, Number value) {
        if (isNullOrEmpty(value)) {
            return;
        }
        this.predicates.add(criteriaBuilder.gt(from.get(propertyName), value));
    }

    /**
     * in
     * 
     * @param propertyName
     *            属性名称
     * @param value
     *            值集合
     */
    public void in(String propertyName, Collection value) {
        if ((value == null) || (value.size() == 0)) {
            return;
        }
        Iterator iterator = value.iterator();
        In in = criteriaBuilder.in(from.get(propertyName));
        while (iterator.hasNext()) {
            in.value(iterator.next());
        }
        this.predicates.add(in);
    }

    /** 直接添加JPA内部的查询条件,用于应付一些复杂查询的情况,例如或 */
    public void addCriterions(Predicate predicate) {
        this.predicates.add(predicate);
    }

    /**
     * 创建查询条件
     * 
     * @return JPA离线查询
     */
    public CriteriaQuery newCriteriaQuery() {
        criteriaQuery.where(predicates.toArray(new Predicate[0]));
        if (!isNullOrEmpty(groupBy)) {
            criteriaQuery.groupBy(from.get(groupBy));
        }
        if (this.orders != null) {
            criteriaQuery.orderBy(orders);
        }
        addLinkCondition(this);
        return criteriaQuery;
    }

    private void addLinkCondition(Query query) {

        Map subQuery = query.linkQuery;
        if (subQuery == null)
            return;

        for (Iterator queryIterator = subQuery.keySet().iterator(); queryIterator.hasNext();) {
            String key = (String) queryIterator.next();
            Query sub = (Query) subQuery.get(key);
            from.join(key);
            criteriaQuery.where(sub.predicates.toArray(new Predicate[0]));
            addLinkCondition(sub);
        }
    }

    public void addOrder(String propertyName, String order) {
        if (order == null || propertyName == null)
            return;

        if (this.orders == null)
            this.orders = new ArrayList();

        if (order.equalsIgnoreCase("asc"))
            this.orders.add(criteriaBuilder.asc(from.get(propertyName)));
        else if (order.equalsIgnoreCase("desc"))
            this.orders.add(criteriaBuilder.desc(from.get(propertyName)));
    }

    public void setOrder(String propertyName, String order) {
        this.orders = null;
        addOrder(propertyName, order);
    }

    public Class getModleClass() {
        return this.clazz;
    }

    public String getProjection() {
        return this.projection;
    }

    public void setProjection(String projection) {
        this.projection = projection;
    }

    public Class getClazz() {
        return this.clazz;
    }

    public List<Order> getOrders() {
        return orders;
    }

    public void setOrders(List<Order> orders) {
        this.orders = orders;
    }

    public EntityManager getEntityManager() {
        return this.entityManager;
    }

    public void setEntityManager(EntityManager em) {
        this.entityManager = em;
    }

    public Root getFrom() {
        return from;
    }

    public List<Predicate> getPredicates() {
        return predicates;
    }

    public void setPredicates(List<Predicate> predicates) {
        this.predicates = predicates;
    }

    public CriteriaQuery getCriteriaQuery() {
        return criteriaQuery;
    }

    public CriteriaBuilder getCriteriaBuilder() {
        return criteriaBuilder;
    }

    public void setFetchModes(List<String> fetchField, List<String> fetchMode) {

    }

    public String getGroupBy() {
        return groupBy;
    }

    public void setGroupBy(String groupBy) {
        this.groupBy = groupBy;
    }

}

 

  1. <?xml version=“1.0” encoding=“UTF-8”?>  
  2. <beans xmlns=”http://www.springframework.org/schema/beans”  
  3.     xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:p=“http://www.springframework.org/schema/p”  
  4.     xmlns:tx=”http://www.springframework.org/schema/tx” xmlns:context=“http://www.springframework.org/schema/context”  
  5.     xmlns:util=”http://www.springframework.org/schema/util”  
  6.     xmlns:aop=”http://www.springframework.org/schema/aop”  
  7.     xsi:schemaLocation=”  
  8.             http://www.springframework.org/schema/beans   
  9.             http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  10.             http://www.springframework.org/schema/tx   
  11.             http://www.springframework.org/schema/tx/spring-tx-3.1.xsd  
  12.             http://www.springframework.org/schema/context  
  13.             http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  14.             http://www.springframework.org/schema/aop   
  15.             http://www.springframework.org/schema/aop/spring-aop.xsd  
  16.             http://www.springframework.org/schema/util   
  17.             http://www.springframework.org/schema/util/spring-util-3.1.xsd”>   
  18.   
  19.     <!– JPA Entity Manager Factory –>  
  20.     <bean id=”entityManagerFactory”  
  21.         class=“org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean”  
  22.         p:packagesToScan=”com.**.model” p:dataSource-ref=“dataSource”  
  23.         p:jpaVendorAdapter-ref=”hibernateVendor” p:jpaPropertyMap-ref=“jpaPropertyMap”/>  
  24.   
  25.     <util:map id=”jpaPropertyMap”>  
  26.         <entry key=”hibernate.hbm2ddl.auto” value=“update” /><!– create,update,none –>  
  27.         <entry key=”hibernate.format_sql” value=“false” />  
  28.         <entry key=”hibernate.show_sql” value=“false” />  
  29.         <entry key=”hibernate.current_session_context_class” value=“org.hibernate.context.internal.ThreadLocalSessionContext”/>  
  30.         <entry key=”hibernate.dialect” value=“org.hibernate.dialect.MySQLDialect” />  
  31.   
  32.         <!– To enable Hibernate’s second level cache and query cache settings –>  
  33.         <entry key=”hibernate.max_fetch_depth” value=“4” />  
  34.         <entry key=”hibernate.cache.use_second_level_cache” value=“true” />  
  35.         <entry key=”hibernate.cache.use_query_cache” value=“true” />  
  36.         <!– <entry key=”hibernate.cache.region.factory_class” value=“org.hibernate.cache.ehcache.EhCacheRegionFactory” /> –>  
  37.         <entry key=”hibernate.cache.region.factory_class” value=“org.hibernate.cache.SingletonEhCacheRegionFactory” />  
  38.     </util:map>  
  39.   
  40.     <bean id=”hibernateVendor”  
  41.         class=“org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter”  
  42.         p:database=”MYSQL” p:showSql=“true” p:generateDdl=“true”  
  43.         p:databasePlatform=”org.hibernate.dialect.MySQLDialect” />  
  44.           
  45.     <bean id=”transactionHandler” class=“com.platform.framework.dao.jpa.TransactionHandler” >  
  46.         <property name=”txmethod”>  
  47.             <list>  
  48.                 <value>insert</value>  
  49.                 <value>update</value>  
  50.                 <value>delete</value>  
  51.             </list>  
  52.         </property>  
  53.         <property name=”entityManagerFactory” ref=“entityManagerFactory”/>  
  54.     </bean>  
  55.     <aop:config>  
  56.         <aop:aspect id=”tran” ref=“transactionHandler”>  
  57.             <aop:pointcut  id=”tranMethod”  
  58.                 expression=”  
  59.                     execution(* com.*.dao.*.*(..))||  
  60.                     execution(* com.*.service.impl.*.*(..))||  
  61.                       
  62.                     execution(* com.*.*.dao.*.*(..))||  
  63.                     execution(* com.*.*.service.impl.*.*(..))||  
  64.                       
  65.                     execution(* com.*.*.*.dao.*.*(..))||  
  66.                     execution(* com.*.*.*.service.impl.*.*(..))||  
  67.                       
  68.                     execution(* com.*.*.*.*.dao.*.*(..))||  
  69.                     execution(* com.*.*.*.*.service.impl.*.*(..))||  
  70.                       
  71.                     execution(* com.*.*.*.*.*.dao.*.*(..))||  
  72.                     execution(* com.*.*.*.*.*.service.impl.*.*(..))||  
  73.                       
  74.                     execution(* com.*.*.*.*.*.*.dao.*.*(..))||  
  75.                     execution(* com.*.*.*.*.*.*.service.impl.*.*(..))||  
  76.                       
  77.                     execution(* com.platform.framework.dao.jpa.BaseDaoImpl.*(..))”/>  
  78.             <aop:around method=”exec”  pointcut-ref=“tranMethod” />  
  79.         </aop:aspect>  
  80.     </aop:config>  
  81.       
  82.     <bean id=”baseDao” class=“com.platform.framework.dao.jpa.BaseDaoImpl”>  
  83.         <property name=”emf” ref=“entityManagerFactory”/>  
  84.     </bean>  
  85. </beans>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.1.xsd
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/util 
            http://www.springframework.org/schema/util/spring-util-3.1.xsd"> 

    <!-- JPA Entity Manager Factory -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        p:packagesToScan="com.**.model" p:dataSource-ref="dataSource"
        p:jpaVendorAdapter-ref="hibernateVendor" p:jpaPropertyMap-ref="jpaPropertyMap"/>

    <util:map id="jpaPropertyMap">
        <entry key="hibernate.hbm2ddl.auto" value="update" /><!-- create,update,none -->
        <entry key="hibernate.format_sql" value="false" />
        <entry key="hibernate.show_sql" value="false" />
        <entry key="hibernate.current_session_context_class" value="org.hibernate.context.internal.ThreadLocalSessionContext"/>
        <entry key="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />

        <!-- To enable Hibernate's second level cache and query cache settings -->
        <entry key="hibernate.max_fetch_depth" value="4" />
        <entry key="hibernate.cache.use_second_level_cache" value="true" />
        <entry key="hibernate.cache.use_query_cache" value="true" />
        <!-- <entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory" /> -->
        <entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.SingletonEhCacheRegionFactory" />
    </util:map>

    <bean id="hibernateVendor"
        class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
        p:database="MYSQL" p:showSql="true" p:generateDdl="true"
        p:databasePlatform="org.hibernate.dialect.MySQLDialect" />

    <bean id="transactionHandler" class="com.platform.framework.dao.jpa.TransactionHandler" >
        <property name="txmethod">
            <list>
                <value>insert</value>
                <value>update</value>
                <value>delete</value>
            </list>
        </property>
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    <aop:config>
        <aop:aspect id="tran" ref="transactionHandler">
            <aop:pointcut  id="tranMethod"
                expression="
                    execution(* com.*.dao.*.*(..))||
                    execution(* com.*.service.impl.*.*(..))||

                    execution(* com.*.*.dao.*.*(..))||
                    execution(* com.*.*.service.impl.*.*(..))||

                    execution(* com.*.*.*.dao.*.*(..))||
                    execution(* com.*.*.*.service.impl.*.*(..))||

                    execution(* com.*.*.*.*.dao.*.*(..))||
                    execution(* com.*.*.*.*.service.impl.*.*(..))||

                    execution(* com.*.*.*.*.*.dao.*.*(..))||
                    execution(* com.*.*.*.*.*.service.impl.*.*(..))||

                    execution(* com.*.*.*.*.*.*.dao.*.*(..))||
                    execution(* com.*.*.*.*.*.*.service.impl.*.*(..))||

                    execution(* com.platform.framework.dao.jpa.BaseDaoImpl.*(..))"/>
            <aop:around method="exec"  pointcut-ref="tranMethod" />
        </aop:aspect>
    </aop:config>

    <bean id="baseDao" class="com.platform.framework.dao.jpa.BaseDaoImpl">
        <property name="emf" ref="entityManagerFactory"/>
    </bean>
</beans>

 

  1. package com.platform.framework.dao.jpa;  
  2.   
  3. import javax.persistence.EntityManager;  
  4. import javax.persistence.EntityManagerFactory;  
  5. import javax.persistence.EntityTransaction;  
  6.   
  7. import org.apache.log4j.Logger;  
  8. import org.aspectj.lang.ProceedingJoinPoint;  
  9. import org.aspectj.lang.Signature;  
  10.   
  11. /** 
  12.  * @describe JPA事务管理 
  13.  * @author lry 
  14.  * @since:2014-05-23 
  15.  *  
  16.  */  
  17. public class TransactionHandler {  
  18.   
  19.     private static final Logger log = Logger  
  20.             .getLogger(TransactionHandler.class);  
  21.   
  22.     private String[] txmethod;// 配置事务的传播特性方法  
  23.   
  24.     private EntityManagerFactory entityManagerFactory;// JPA工厂  
  25.   
  26.     public Object exec(ProceedingJoinPoint point) throws Throwable {  
  27.   
  28.         Signature signature = point.getSignature();  
  29.          log.debug(point.getTarget().getClass().getName() + ”.”  
  30.          + signature.getName() + ”()”);  
  31.         Boolean isTransaction = false;  
  32.         for (String method : txmethod) {  
  33.             if (signature.getName().startsWith(method)) {// 以method开头的方法打开事务  
  34.                 isTransaction = true;  
  35.                 break;  
  36.             }  
  37.         }  
  38.   
  39.         // JPA->Hibernate  
  40.         if (point.getTarget() instanceof EntityManagerFactoryProxy) {  
  41.   
  42.             // 获得被代理对象  
  43.             EntityManagerFactoryProxy emfp = (EntityManagerFactoryProxy) point  
  44.                     .getTarget();  
  45.             EntityManager em = emfp.getEntityManager();  
  46.             if (em != null) {// 如果对象已经有em了就不管  
  47.                 return point.proceed();  
  48.             } else {  
  49.                 em = entityManagerFactory.createEntityManager();  
  50.             }  
  51.              log.debug(”JPA->Hibernate open connection…”);  
  52.             if (isTransaction) {  
  53.                 EntityTransaction t = null;  
  54.                 try {  
  55.   
  56.                     // 打开连接并开启事务  
  57.                      log.debug(”JPA->Hibernate begin transaction…”);  
  58.                     t = em.getTransaction();  
  59.                     if (!t.isActive())  
  60.                         t.begin();  
  61.                     emfp.setEntityManager(em);  
  62.                     Object obj = point.proceed();  
  63.   
  64.                     // 提交事务  
  65.                     log.debug(”JPA->Hibernate commit…”);  
  66.                     t.commit();  
  67.                     return obj;  
  68.                 } catch (Exception e) {  
  69.                     if (t != null) {  
  70.                         log.debug(”JPA->Hibernate error…,rollback…”  
  71.                                 + e.getMessage());  
  72.                         t.rollback();  
  73.                     }  
  74.                     e.printStackTrace();  
  75.                     throw e;  
  76.                 } finally {  
  77.                     if (em != null && em.isOpen()) {// 关闭连接  
  78.                         em.close();  
  79.                         log.debug(”JPA->Hibernate close connection…”);  
  80.                     }  
  81.                     emfp.setEntityManager(null);  
  82.                 }  
  83.             } else {  
  84.                 try {  
  85.                     emfp.setEntityManager(em);  
  86.                     return point.proceed();  
  87.                 } catch (Exception e) {  
  88.                     log.debug(”JPA->Hibernate error…” + e.getMessage());  
  89.                     e.printStackTrace();  
  90.                     throw e;  
  91.                 } finally {  
  92.                     if (em != null && em.isOpen()) {// 关闭连接  
  93.                         em.close();  
  94.                         log.debug(”JPA->Hibernate close connection…”);  
  95.                     }  
  96.                     emfp.setEntityManager(null);  
  97.                 }  
  98.             }  
  99.         } else {  
  100.             return point.proceed();  
  101.         }  
  102.     }  
  103.   
  104.     public String[] getTxmethod() {  
  105.         return txmethod;  
  106.     }  
  107.   
  108.     public void setTxmethod(String[] txmethod) {  
  109.         this.txmethod = txmethod;  
  110.     }  
  111.   
  112.     public void setEntityManagerFactory(  
  113.             EntityManagerFactory entityManagerFactory) {  
  114.         this.entityManagerFactory = entityManagerFactory;  
  115.     }  
  116.   
  117. }  
package com.platform.framework.dao.jpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;

/**
 * @describe JPA事务管理
 * @author lry
 * @since:2014-05-23
 * 
 */
public class TransactionHandler {

    private static final Logger log = Logger
            .getLogger(TransactionHandler.class);

    private String[] txmethod;// 配置事务的传播特性方法

    private EntityManagerFactory entityManagerFactory;// JPA工厂

    public Object exec(ProceedingJoinPoint point) throws Throwable {

        Signature signature = point.getSignature();
         log.debug(point.getTarget().getClass().getName() + "."
         + signature.getName() + "()");
        Boolean isTransaction = false;
        for (String method : txmethod) {
            if (signature.getName().startsWith(method)) {// 以method开头的方法打开事务
                isTransaction = true;
                break;
            }
        }

        // JPA->Hibernate
        if (point.getTarget() instanceof EntityManagerFactoryProxy) {

            // 获得被代理对象
            EntityManagerFactoryProxy emfp = (EntityManagerFactoryProxy) point
                    .getTarget();
            EntityManager em = emfp.getEntityManager();
            if (em != null) {// 如果对象已经有em了就不管
                return point.proceed();
            } else {
                em = entityManagerFactory.createEntityManager();
            }
             log.debug("JPA->Hibernate open connection...");
            if (isTransaction) {
                EntityTransaction t = null;
                try {

                    // 打开连接并开启事务
                     log.debug("JPA->Hibernate begin transaction...");
                    t = em.getTransaction();
                    if (!t.isActive())
                        t.begin();
                    emfp.setEntityManager(em);
                    Object obj = point.proceed();

                    // 提交事务
                    log.debug("JPA->Hibernate commit...");
                    t.commit();
                    return obj;
                } catch (Exception e) {
                    if (t != null) {
                        log.debug("JPA->Hibernate error...,rollback..."
                                + e.getMessage());
                        t.rollback();
                    }
                    e.printStackTrace();
                    throw e;
                } finally {
                    if (em != null && em.isOpen()) {// 关闭连接
                        em.close();
                        log.debug("JPA->Hibernate close connection...");
                    }
                    emfp.setEntityManager(null);
                }
            } else {
                try {
                    emfp.setEntityManager(em);
                    return point.proceed();
                } catch (Exception e) {
                    log.debug("JPA->Hibernate error..." + e.getMessage());
                    e.printStackTrace();
                    throw e;
                } finally {
                    if (em != null && em.isOpen()) {// 关闭连接
                        em.close();
                        log.debug("JPA->Hibernate close connection...");
                    }
                    emfp.setEntityManager(null);
                }
            }
        } else {
            return point.proceed();
        }
    }

    public String[] getTxmethod() {
        return txmethod;
    }

    public void setTxmethod(String[] txmethod) {
        this.txmethod = txmethod;
    }

    public void setEntityManagerFactory(
            EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

}

 

EntityManager管理器,通过spring管理

  1. package com.platform.framework.dao.jpa;  
  2.   
  3. import java.util.Collection;  
  4.   
  5. import javax.persistence.EntityManager;  
  6. import javax.persistence.EntityManagerFactory;  
  7.   
  8. /** 
  9.  * EntityManager管理器 
  10.  *  
  11.  * @author:yangjian1004 
  12.  * @since:2011-11-30 16:14:24 AM 
  13.  */  
  14. public class EntityManagerFactoryProxy {  
  15.   
  16.     private static ThreadLocal<EntityManager> emThreadLocal = new ThreadLocal<EntityManager>();  
  17.     private static EntityManagerFactory emf;  
  18.   
  19.     public void setEmf(EntityManagerFactory emf) {  
  20.         EntityManagerFactoryProxy.emf = emf;  
  21.     }  
  22.   
  23.     public static EntityManagerFactory getEmf() {  
  24.         return emf;  
  25.     }  
  26.   
  27.     public EntityManager getEntityManager() {  
  28.         return emThreadLocal.get();  
  29.     }  
  30.   
  31.     public void setEntityManager(EntityManager em) {  
  32.         emThreadLocal.set(em);  
  33.     }  
  34.   
  35.     /** 
  36.      * 创建查询条件 
  37.      *  
  38.      * @param name 
  39.      *            字段名称 
  40.      * @param values 
  41.      *            字段值 
  42.      */  
  43.     public String createInCondition(String name, Collection<String> values) {  
  44.         if (values == null || values.size() == 0) {  
  45.             return “1<>1”;  
  46.         }  
  47.         StringBuffer sb = new StringBuffer();  
  48.         sb.append(name + ” in(“);  
  49.         for (String id : values) {  
  50.             sb.append(”’” + id + “’,”);  
  51.         }  
  52.         String hsqlCondition = sb.substring(0, sb.length() - 1) + “)”;  
  53.         return hsqlCondition;  
  54.     }  
  55. }  
package com.platform.framework.dao.jpa;

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 * EntityManager管理器
 * 
 * @author:yangjian1004
 * @since:2011-11-30 16:14:24 AM
 */
public class EntityManagerFactoryProxy {

    private static ThreadLocal<EntityManager> emThreadLocal = new ThreadLocal<EntityManager>();
    private static EntityManagerFactory emf;

    public void setEmf(EntityManagerFactory emf) {
        EntityManagerFactoryProxy.emf = emf;
    }

    public static EntityManagerFactory getEmf() {
        return emf;
    }

    public EntityManager getEntityManager() {
        return emThreadLocal.get();
    }

    public void setEntityManager(EntityManager em) {
        emThreadLocal.set(em);
    }

    /**
     * 创建查询条件
     * 
     * @param name
     *            字段名称
     * @param values
     *            字段值
     */
    public String createInCondition(String name, Collection<String> values) {
        if (values == null || values.size() == 0) {
            return "1<>1";
        }
        StringBuffer sb = new StringBuffer();
        sb.append(name + " in(");
        for (String id : values) {
            sb.append("'" + id + "',");
        }
        String hsqlCondition = sb.substring(0, sb.length() - 1) + ")";
        return hsqlCondition;
    }
}

 

Page分页和结果封装类

  1. package com.platform.framework.dao.jpa;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. /** 
  8.  * Page基类<br> 
  9.  *  
  10.  * @describe:分页 
  11.  */  
  12. public class Page<T> implements Serializable {  
  13.   
  14.     private static final long serialVersionUID = 665620345605746930L;  
  15.     /** 总条数 */  
  16.     private int count;  
  17.     /** 页码 */  
  18.     private int pageNo;  
  19.     /** 每页显示多少条 */  
  20.     private int rowsPerPage;  
  21.     /** 总页数 */  
  22.     private int totalPageCount;  
  23.     /** 起始条数 */  
  24.     private int firstRow;  
  25.     /** 结束条数 */  
  26.     private int lastRow;  
  27.     /** 查询结果集合形式的结果 */  
  28.     private List<T> result;  
  29.     /** 查询结果对象形式的结果 */  
  30.     public Object obj;  
  31.   
  32.     public Integer code; // 返回码  
  33.     private boolean success = true;  
  34.     private String message;  
  35.   
  36.     public Page() {  
  37.     }  
  38.   
  39.     public Page(List<T> list) {  
  40.         this(list.size(), 1, list.size(), list);  
  41.     }  
  42.   
  43.     public Page(int count, int pageNo, int rowsPerPage, List<T> result) {  
  44.         if (rowsPerPage < 1) {  
  45.             rowsPerPage = 1;  
  46.         }  
  47.         this.count = count;  
  48.         this.pageNo = pageNo;  
  49.         this.result = result;  
  50.         this.rowsPerPage = rowsPerPage;  
  51.         if (this.result == null)  
  52.             this.result = new ArrayList<T>();  
  53.         totalPageCount = count / rowsPerPage;  
  54.         if (count - (count / rowsPerPage) * rowsPerPage > 0)  
  55.             totalPageCount++;  
  56.         if (count == 0) {  
  57.             totalPageCount = 0;  
  58.             pageNo = 0;  
  59.         }  
  60.   
  61.         firstRow = (pageNo - 1) * rowsPerPage + 1;  
  62.         if (count == 0) {  
  63.             firstRow = 0;  
  64.         }  
  65.         lastRow = (pageNo) * rowsPerPage;  
  66.         if (lastRow > count) {  
  67.             lastRow = count;  
  68.         }  
  69.     }  
  70.   
  71.     /** 返回每页的条数 */  
  72.     public int getCount() {  
  73.         return count;  
  74.     }  
  75.   
  76.     public List<T> getResult() {  
  77.         return result;  
  78.     }  
  79.   
  80.     public int getPageNo() {  
  81.         return pageNo;  
  82.     }  
  83.   
  84.     /** 返回每页的条数 */  
  85.     public int getRowsPerPage() {  
  86.         return rowsPerPage;  
  87.     }  
  88.   
  89.     /** 返回总的页数 */  
  90.     public int getTotalPageCount() {  
  91.         return totalPageCount;  
  92.     }  
  93.   
  94.     public void setPageNo(int pageNo) {  
  95.         this.pageNo = pageNo;  
  96.     }  
  97.   
  98.     public void setRowsPerPage(int rowsPerPage) {  
  99.         this.rowsPerPage = rowsPerPage;  
  100.     }  
  101.   
  102.     public int getFirstRow() {  
  103.         return firstRow;  
  104.     }  
  105.   
  106.     public int getLastRow() {  
  107.         return lastRow;  
  108.     }  
  109.   
  110.     public void setFirstRow(int firstRow) {  
  111.         this.firstRow = firstRow;  
  112.     }  
  113.   
  114.     public void setLastRow(int lastRow) {  
  115.         this.lastRow = lastRow;  
  116.     }  
  117.   
  118.     public void setCount(int count) {  
  119.         this.count = count;  
  120.     }  
  121.   
  122.     public void setTotalPageCount(int totalPageCount) {  
  123.         this.totalPageCount = totalPageCount;  
  124.     }  
  125.   
  126.     public void setResult(List<T> result) {  
  127.         this.result = result;  
  128.     }  
  129.   
  130.     public Object getObj() {  
  131.         return obj;  
  132.     }  
  133.   
  134.     public void setObj(Object obj) {  
  135.         this.obj = obj;  
  136.     }  
  137.   
  138.     public boolean isSuccess() {  
  139.         return success;  
  140.     }  
  141.   
  142.     public void setSuccess(boolean success) {  
  143.         this.success = success;  
  144.     }  
  145.   
  146.     public String getMessage() {  
  147.         return message;  
  148.     }  
  149.   
  150.     public void setMessage(String message) {  
  151.         this.message = message;  
  152.     }  
  153.   
  154.     /** 
  155.      * 计算起始条数 
  156.      */  
  157.     public static int calc(int pageNo, int rowsPerPage, int count) {  
  158.         if (pageNo <= 0)  
  159.             pageNo = 1;  
  160.         if (rowsPerPage <= 0)  
  161.             rowsPerPage = 10;  
  162.   
  163.         // 当把最后一页数据删除以后,页码会停留在最后一个上必须减一  
  164.         int totalPageCount = count / rowsPerPage;  
  165.         if (pageNo > totalPageCount && (count % rowsPerPage == 0)) {  
  166.             pageNo = totalPageCount;  
  167.         }  
  168.         if (pageNo - totalPageCount > 2) {  
  169.             pageNo = totalPageCount + 1;  
  170.         }  
  171.         int firstRow = (pageNo - 1) * rowsPerPage;  
  172.         if (firstRow < 0) {  
  173.             firstRow = 0;  
  174.         }  
  175.         return firstRow;  
  176.     }  
  177.   
  178. }  
package com.platform.framework.dao.jpa;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Page基类<br>
 * 
 * @describe:分页
 */
public class Page<T> implements Serializable {

    private static final long serialVersionUID = 665620345605746930L;
    /** 总条数 */
    private int count;
    /** 页码 */
    private int pageNo;
    /** 每页显示多少条 */
    private int rowsPerPage;
    /** 总页数 */
    private int totalPageCount;
    /** 起始条数 */
    private int firstRow;
    /** 结束条数 */
    private int lastRow;
    /** 查询结果集合形式的结果 */
    private List<T> result;
    /** 查询结果对象形式的结果 */
    public Object obj;

    public Integer code; // 返回码
    private boolean success = true;
    private String message;

    public Page() {
    }

    public Page(List<T> list) {
        this(list.size(), 1, list.size(), list);
    }

    public Page(int count, int pageNo, int rowsPerPage, List<T> result) {
        if (rowsPerPage < 1) {
            rowsPerPage = 1;
        }
        this.count = count;
        this.pageNo = pageNo;
        this.result = result;
        this.rowsPerPage = rowsPerPage;
        if (this.result == null)
            this.result = new ArrayList<T>();
        totalPageCount = count / rowsPerPage;
        if (count - (count / rowsPerPage) * rowsPerPage > 0)
            totalPageCount++;
        if (count == 0) {
            totalPageCount = 0;
            pageNo = 0;
        }

        firstRow = (pageNo - 1) * rowsPerPage + 1;
        if (count == 0) {
            firstRow = 0;
        }
        lastRow = (pageNo) * rowsPerPage;
        if (lastRow > count) {
            lastRow = count;
        }
    }

    /** 返回每页的条数 */
    public int getCount() {
        return count;
    }

    public List<T> getResult() {
        return result;
    }

    public int getPageNo() {
        return pageNo;
    }

    /** 返回每页的条数 */
    public int getRowsPerPage() {
        return rowsPerPage;
    }

    /** 返回总的页数 */
    public int getTotalPageCount() {
        return totalPageCount;
    }

    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
    }

    public void setRowsPerPage(int rowsPerPage) {
        this.rowsPerPage = rowsPerPage;
    }

    public int getFirstRow() {
        return firstRow;
    }

    public int getLastRow() {
        return lastRow;
    }

    public void setFirstRow(int firstRow) {
        this.firstRow = firstRow;
    }

    public void setLastRow(int lastRow) {
        this.lastRow = lastRow;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public void setTotalPageCount(int totalPageCount) {
        this.totalPageCount = totalPageCount;
    }

    public void setResult(List<T> result) {
        this.result = result;
    }

    public Object getObj() {
        return obj;
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * 计算起始条数
     */
    public static int calc(int pageNo, int rowsPerPage, int count) {
        if (pageNo <= 0)
            pageNo = 1;
        if (rowsPerPage <= 0)
            rowsPerPage = 10;

        // 当把最后一页数据删除以后,页码会停留在最后一个上必须减一
        int totalPageCount = count / rowsPerPage;
        if (pageNo > totalPageCount && (count % rowsPerPage == 0)) {
            pageNo = totalPageCount;
        }
        if (pageNo - totalPageCount > 2) {
            pageNo = totalPageCount + 1;
        }
        int firstRow = (pageNo - 1) * rowsPerPage;
        if (firstRow < 0) {
            firstRow = 0;
        }
        return firstRow;
    }

}

 

IBaseDao接口实现了BaseDaoImpl

  1. package com.platform.framework.dao.jpa;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5.   
  6. import javax.persistence.EntityManager;  
  7. import javax.persistence.criteria.CriteriaQuery;  
  8. import javax.persistence.criteria.Predicate;  
  9. import javax.persistence.criteria.Selection;  
  10. import javax.persistence.metamodel.EntityType;  
  11.   
  12. import org.apache.log4j.Logger;  
  13.   
  14. import com.google.common.base.Strings;  
  15. /** 
  16.  * IBaseDao接口实现了BaseDaoImpl类<br> 
  17.  */  
  18. @SuppressWarnings({ “unchecked”“rawtypes” })  
  19. public class BaseDaoImpl<T> extends EntityManagerFactoryProxy implements IBaseDao {  
  20.   
  21.     private static Logger log = Logger.getLogger(BaseDaoImpl.class);  
  22.   
  23.     /** 每次批量操作数 */  
  24.     private int batchSize = 50;  
  25.   
  26.     /** 设置每次操作数 */  
  27.     public void setBatchSize(int batchSize) {  
  28.         this.batchSize = batchSize;  
  29.     }  
  30.   
  31.     public <E> E get(Class clazz, Serializable id) {  
  32.         return (E) getEntityManager().find(clazz, id);  
  33.     }  
  34.   
  35.     /** 
  36.      * 插入记录 
  37.      *  
  38.      * @param entity 
  39.      *            要插入的记录 
  40.      */  
  41.     public void insert(Object entity) {  
  42.         if (entity instanceof List) {  
  43.             insertList((List) entity);  
  44.             return;  
  45.         } else if (entity instanceof Object[]) {  
  46.             return;  
  47.         }  
  48.         try {  
  49.             getEntityManager().persist(entity);  
  50.         } catch (Exception e) {  
  51.             e.printStackTrace();  
  52.         }  
  53.     }  
  54.   
  55.     /** 
  56.      * 批量增加 
  57.      *  
  58.      * @param list 
  59.      *            要新增的数据 
  60.      */  
  61.     public void insertList(List list) {  
  62.         EntityManager entityManager = getEntityManager();  
  63.         if (list == null || list.size() == 0) {  
  64.             return;  
  65.         }  
  66.         int i = 0;  
  67.         for (Object o : list) {  
  68.             insert(o);  
  69.             if (i % batchSize == 0) {  
  70.                 entityManager.flush();  
  71.             }  
  72.             i++;  
  73.         }  
  74.         log.debug(list.get(0).getClass() + “批量增加数据” + i + “条”);  
  75.     }  
  76.   
  77.     /** 
  78.      * 更新记录 
  79.      *  
  80.      * @param entity 
  81.      *            要更新的记录 
  82.      */  
  83.     public void update(Object entity) {  
  84.         if (entity instanceof List) {  
  85.             this.updateList((List) entity);  
  86.             return;  
  87.         }  
  88.         getEntityManager().merge(entity);  
  89.     }  
  90.   
  91.     /** 更新list */  
  92.     public void updateList(List list) {  
  93.         for (Object entity : list) {  
  94.             this.update(entity);  
  95.         }  
  96.     }  
  97.   
  98.     /** 
  99.      * 删除记录 
  100.      *  
  101.      * @param entity 
  102.      *            要删除的记录 
  103.      */  
  104.     public void delete(Object entity) {  
  105.         if (entity instanceof List) {  
  106.             List list = (List) entity;  
  107.             for (Object o : list) {  
  108.                 getEntityManager().remove(o);  
  109.             }  
  110.         } else {  
  111.             getEntityManager().remove(entity);  
  112.         }  
  113.     }  
  114.   
  115.     public <E extends Serializable> List<E> query(String jpql) {  
  116.         return getEntityManager().createQuery(jpql).getResultList();  
  117.     }  
  118.   
  119.     public Integer updateJpql(String jpql) {  
  120.         return getEntityManager().createQuery(jpql).executeUpdate();  
  121.     }  
  122.   
  123.     public Integer updateSql(String sql) {  
  124.         return getEntityManager().createNativeQuery(sql).executeUpdate();  
  125.     }  
  126.   
  127.     public <E extends Serializable> List<E> queryBySql(String sql) {  
  128.         return getEntityManager().createNativeQuery(sql).getResultList();  
  129.     }  
  130.   
  131.     /** 
  132.      * 查询记录 
  133.      *  
  134.      * @param clazz 
  135.      *            要查询的实体类 
  136.      * @param hqlCondition 
  137.      *            查询条件 
  138.      */  
  139.     public <E extends Serializable> List<E> query(Class clazz, String hqlCondition) {  
  140.         return getEntityManager().createQuery(“select t from ” + clazz.getName() + “ as t where ” + hqlCondition)  
  141.                 .getResultList();  
  142.     }  
  143.   
  144.     public void delete(Class entity, String jpqlCondition) {  
  145.         if (Strings.isNullOrEmpty(jpqlCondition)) {  
  146.             jpqlCondition = ”1=1”;  
  147.         }  
  148.         int no = updateJpql(“delete ” + entity.getName() + “ where ” + jpqlCondition);  
  149.         log.debug(entity.getName() + ”删除” + no + “条数据”);  
  150.     }  
  151.   
  152.     /** 
  153.      * 根据ids删除数据 
  154.      *  
  155.      * @param entity 
  156.      *            删除实体类 
  157.      * @param ids 
  158.      *            删除条件 
  159.      */  
  160.     public void delete(Class entity, List ids) {  
  161.         String idName = getIdName(entity, getEntityManager());  
  162.         StringBuffer sb = new StringBuffer();  
  163.         sb.append(idName + ” in(“);  
  164.         for (int i = 0; i < ids.size(); i++) {  
  165.             sb.append(”’” + ids.get(i) + “’,”);  
  166.         }  
  167.         String jpqlCondition = sb.substring(0, sb.length() - 1) + “)”;  
  168.         delete(entity, jpqlCondition);  
  169.     }  
  170.   
  171.     public <E extends Serializable> List<E> query(String jpql, int firstResult, int maxResults) {  
  172.         List result = getEntityManager().createQuery(jpql).setFirstResult(firstResult).setMaxResults(maxResults)  
  173.                 .getResultList();  
  174.         return result;  
  175.     }  
  176.   
  177.     public <E extends Serializable> List<E> queryBySql(String sql, int firstResult, int maxResults) {  
  178.         return getEntityManager().createNativeQuery(sql).setFirstResult(firstResult).setMaxResults(maxResults)  
  179.                 .getResultList();  
  180.     }  
  181.   
  182.     public <E extends Serializable> List<E> queryAll(Class clazz) {  
  183.         CriteriaQuery criteriaQuery = getEntityManager().getCriteriaBuilder().createQuery(clazz);  
  184.         criteriaQuery.from(clazz);  
  185.         return getEntityManager().createQuery(criteriaQuery).getResultList();  
  186.     }  
  187.   
  188.     public Page queryPageByJpql(String jpql, int pageNo, int rowsPerPage) {  
  189.         if (pageNo <= 0)  
  190.             pageNo = 1;  
  191.         if (rowsPerPage <= 0)  
  192.             rowsPerPage = 7;  
  193.         log.debug(”—–开始查询,页码:” + pageNo + “,每页显示:” + rowsPerPage + “—-“);  
  194.   
  195.         String countJpql = ”select count(*) from (“ + jpql + “)”;  
  196.         int count = getCount(countJpql).intValue();  
  197.   
  198.         // 当把最后一页数据删除以后,页码会停留在最后一个上必须减一  
  199.         int totalPageCount = count / rowsPerPage;  
  200.         if (pageNo > totalPageCount && (count % rowsPerPage == 0)) {  
  201.             pageNo = totalPageCount;  
  202.         }  
  203.         if (pageNo - totalPageCount > 2) {  
  204.             pageNo = totalPageCount + 1;  
  205.         }  
  206.         int firstResult = (pageNo - 1) * rowsPerPage;  
  207.         if (firstResult < 0) {  
  208.             firstResult = 0;  
  209.         }  
  210.         List result = getEntityManager().createQuery(jpql).setFirstResult(firstResult).setMaxResults(rowsPerPage)  
  211.                 .getResultList();  
  212.         return new Page(count, pageNo, rowsPerPage, result);  
  213.     }  
  214.   
  215.     public Long getCount(String jpql) {  
  216.         return (Long) getEntityManager().createQuery(jpql).getResultList().get(0);  
  217.     }  
  218.   
  219.     /*** 
  220.      *  
  221.      * @Method updateJpql 
  222.      * @Description 根据传入的带有占位符的sql语句, 做增删改操作 例如 
  223.      *              updateJpql(“update user t set t.name=? where t.id=?” 
  224.      *              ,{[zhongxiang],[23]}) 
  225.      * @Author 钟翔/zhongxiang 
  226.      * @Date 2012-8-9 下午3:38:35 
  227.      * @param jpql 
  228.      *            占位符式的sql 
  229.      * @param paramList 
  230.      *            list里面装有[zhongxiang , 23] 
  231.      */  
  232.     public void updateJpql(String jpql, List paramList) {  
  233.         javax.persistence.Query query = getEntityManager().createQuery(jpql);  
  234.         for (int i = 0; i < paramList.size(); i++) {  
  235.             query.setParameter(i + 1, paramList.get(i));  
  236.         }  
  237.         query.executeUpdate();  
  238.     }  
  239.   
  240.     /** 
  241.      * 统计记录 
  242.      *  
  243.      * @param query 
  244.      *            统计条件 
  245.      */  
  246.     public Long getCount(Query query) {  
  247.         Selection selection = query.getCriteriaQuery().getSelection();  
  248.         query.getCriteriaQuery().select(query.getCriteriaBuilder().count(query.getFrom()));  
  249.         Long count = (Long) getEntityManager().createQuery(query.newCriteriaQuery()).getResultList().get(0);  
  250.         query.getCriteriaQuery().select(selection);  
  251.         return count;  
  252.     }  
  253.   
  254.     /** 
  255.      * 分页查询 
  256.      *  
  257.      * @param query 
  258.      *            查询条件 
  259.      * @param pageNo 
  260.      *            页号 
  261.      * @param rowsPerPage 
  262.      *            每页显示条数 
  263.      */  
  264.     public Page queryPage(Query query, int pageNo, int rowsPerPage) {  
  265.         if (pageNo <= 0)  
  266.             pageNo = 1;  
  267.         if (rowsPerPage <= 0)  
  268.             rowsPerPage = 7;  
  269.         log.debug(query.getClazz() + ”—–开始查询,页码:” + pageNo + “,每页显示:” + rowsPerPage + “—-“);  
  270.         log.debug(”查询条件:”);  
  271.         for (Predicate cri : query.getPredicates())  
  272.             log.debug(cri);  
  273.   
  274.         int count = getCount(query).intValue();  
  275.   
  276.         // 当把最后一页数据删除以后,页码会停留在最后一个上必须减一  
  277.         int totalPageCount = count / rowsPerPage;  
  278.         if (pageNo > totalPageCount && (count % rowsPerPage == 0)) {  
  279.             pageNo = totalPageCount;  
  280.         }  
  281.         if (pageNo - totalPageCount > 2) {  
  282.             pageNo = totalPageCount + 1;  
  283.         }  
  284.         int firstResult = (pageNo - 1) * rowsPerPage;  
  285.         if (firstResult < 0) {  
  286.             firstResult = 0;  
  287.         }  
  288.         List result = getEntityManager().createQuery(query.newCriteriaQuery()).setFirstResult(firstResult)  
  289.                 .setMaxResults(rowsPerPage).getResultList();  
  290.         return new Page(count, pageNo, rowsPerPage, result);  
  291.     }  
  292.   
  293.     /** 
  294.      * 根据query查找记录 
  295.      *  
  296.      * @param query 
  297.      *            查询条件 
  298.      * @param firstResult 
  299.      *            起始行 
  300.      * @param maxResults 
  301.      *            结束行 
  302.      */  
  303.     public <E extends Serializable> List<E> query(Query query, int firstResult, int maxResults) {  
  304.         List result = getEntityManager().createQuery(query.newCriteriaQuery()).setFirstResult(firstResult)  
  305.                 .setMaxResults(maxResults).getResultList();  
  306.         return result;  
  307.     }  
  308.   
  309.     /** 
  310.      * 根据query查找记录 
  311.      *  
  312.      * @param query 
  313.      *            查询条件 
  314.      */  
  315.     public <E extends Serializable> List<E> query(Query query) {  
  316.         return getEntityManager().createQuery(query.newCriteriaQuery()).getResultList();  
  317.     }  
  318.       
  319.     /** 
  320.      * 获得主键名称 
  321.      *  
  322.      * @param clazz 
  323.      *            操作是实体对象 
  324.      * @param EntityManager 
  325.      *            jpa的entityManager工厂 
  326.      * @return 初建名称 
  327.      * */  
  328.     public static String getIdName(Class clazz, EntityManager entityManager) {  
  329.         EntityType entityType = entityManager.getMetamodel().entity(clazz);  
  330.         return entityType.getId(entityType.getIdType().getJavaType()).getName();  
  331.     }  
  332. }  
package com.platform.framework.dao.jpa;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Selection;
import javax.persistence.metamodel.EntityType;

import org.apache.log4j.Logger;

import com.google.common.base.Strings;
/**
 * IBaseDao接口实现了BaseDaoImpl类<br>
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class BaseDaoImpl<T> extends EntityManagerFactoryProxy implements IBaseDao {

    private static Logger log = Logger.getLogger(BaseDaoImpl.class);

    /** 每次批量操作数 */
    private int batchSize = 50;

    /** 设置每次操作数 */
    public void setBatchSize(int batchSize) {
        this.batchSize = batchSize;
    }

    public <E> E get(Class clazz, Serializable id) {
        return (E) getEntityManager().find(clazz, id);
    }

    /**
     * 插入记录
     * 
     * @param entity
     *            要插入的记录
     */
    public void insert(Object entity) {
        if (entity instanceof List) {
            insertList((List) entity);
            return;
        } else if (entity instanceof Object[]) {
            return;
        }
        try {
            getEntityManager().persist(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量增加
     * 
     * @param list
     *            要新增的数据
     */
    public void insertList(List list) {
        EntityManager entityManager = getEntityManager();
        if (list == null || list.size() == 0) {
            return;
        }
        int i = 0;
        for (Object o : list) {
            insert(o);
            if (i % batchSize == 0) {
                entityManager.flush();
            }
            i++;
        }
        log.debug(list.get(0).getClass() + "批量增加数据" + i + "条");
    }

    /**
     * 更新记录
     * 
     * @param entity
     *            要更新的记录
     */
    public void update(Object entity) {
        if (entity instanceof List) {
            this.updateList((List) entity);
            return;
        }
        getEntityManager().merge(entity);
    }

    /** 更新list */
    public void updateList(List list) {
        for (Object entity : list) {
            this.update(entity);
        }
    }

    /**
     * 删除记录
     * 
     * @param entity
     *            要删除的记录
     */
    public void delete(Object entity) {
        if (entity instanceof List) {
            List list = (List) entity;
            for (Object o : list) {
                getEntityManager().remove(o);
            }
        } else {
            getEntityManager().remove(entity);
        }
    }

    public <E extends Serializable> List<E> query(String jpql) {
        return getEntityManager().createQuery(jpql).getResultList();
    }

    public Integer updateJpql(String jpql) {
        return getEntityManager().createQuery(jpql).executeUpdate();
    }

    public Integer updateSql(String sql) {
        return getEntityManager().createNativeQuery(sql).executeUpdate();
    }

    public <E extends Serializable> List<E> queryBySql(String sql) {
        return getEntityManager().createNativeQuery(sql).getResultList();
    }

    /**
     * 查询记录
     * 
     * @param clazz
     *            要查询的实体类
     * @param hqlCondition
     *            查询条件
     */
    public <E extends Serializable> List<E> query(Class clazz, String hqlCondition) {
        return getEntityManager().createQuery("select t from " + clazz.getName() + " as t where " + hqlCondition)
                .getResultList();
    }

    public void delete(Class entity, String jpqlCondition) {
        if (Strings.isNullOrEmpty(jpqlCondition)) {
            jpqlCondition = "1=1";
        }
        int no = updateJpql("delete " + entity.getName() + " where " + jpqlCondition);
        log.debug(entity.getName() + "删除" + no + "条数据");
    }

    /**
     * 根据ids删除数据
     * 
     * @param entity
     *            删除实体类
     * @param ids
     *            删除条件
     */
    public void delete(Class entity, List ids) {
        String idName = getIdName(entity, getEntityManager());
        StringBuffer sb = new StringBuffer();
        sb.append(idName + " in(");
        for (int i = 0; i < ids.size(); i++) {
            sb.append("'" + ids.get(i) + "',");
        }
        String jpqlCondition = sb.substring(0, sb.length() - 1) + ")";
        delete(entity, jpqlCondition);
    }

    public <E extends Serializable> List<E> query(String jpql, int firstResult, int maxResults) {
        List result = getEntityManager().createQuery(jpql).setFirstResult(firstResult).setMaxResults(maxResults)
                .getResultList();
        return result;
    }

    public <E extends Serializable> List<E> queryBySql(String sql, int firstResult, int maxResults) {
        return getEntityManager().createNativeQuery(sql).setFirstResult(firstResult).setMaxResults(maxResults)
                .getResultList();
    }

    public <E extends Serializable> List<E> queryAll(Class clazz) {
        CriteriaQuery criteriaQuery = getEntityManager().getCriteriaBuilder().createQuery(clazz);
        criteriaQuery.from(clazz);
        return getEntityManager().createQuery(criteriaQuery).getResultList();
    }

    public Page queryPageByJpql(String jpql, int pageNo, int rowsPerPage) {
        if (pageNo <= 0)
            pageNo = 1;
        if (rowsPerPage <= 0)
            rowsPerPage = 7;
        log.debug("-----开始查询,页码:" + pageNo + ",每页显示:" + rowsPerPage + "----");

        String countJpql = "select count(*) from (" + jpql + ")";
        int count = getCount(countJpql).intValue();

        // 当把最后一页数据删除以后,页码会停留在最后一个上必须减一
        int totalPageCount = count / rowsPerPage;
        if (pageNo > totalPageCount && (count % rowsPerPage == 0)) {
            pageNo = totalPageCount;
        }
        if (pageNo - totalPageCount > 2) {
            pageNo = totalPageCount + 1;
        }
        int firstResult = (pageNo - 1) * rowsPerPage;
        if (firstResult < 0) {
            firstResult = 0;
        }
        List result = getEntityManager().createQuery(jpql).setFirstResult(firstResult).setMaxResults(rowsPerPage)
                .getResultList();
        return new Page(count, pageNo, rowsPerPage, result);
    }

    public Long getCount(String jpql) {
        return (Long) getEntityManager().createQuery(jpql).getResultList().get(0);
    }

    /***
     * 
     * @Method updateJpql
     * @Description 根据传入的带有占位符的sql语句, 做增删改操作 例如
     *              updateJpql("update user t set t.name=? where t.id=?"
     *              ,{[zhongxiang],[23]})
     * @Author 钟翔/zhongxiang
     * @Date 2012-8-9 下午3:38:35
     * @param jpql
     *            占位符式的sql
     * @param paramList
     *            list里面装有[zhongxiang , 23]
     */
    public void updateJpql(String jpql, List paramList) {
        javax.persistence.Query query = getEntityManager().createQuery(jpql);
        for (int i = 0; i < paramList.size(); i++) {
            query.setParameter(i + 1, paramList.get(i));
        }
        query.executeUpdate();
    }

    /**
     * 统计记录
     * 
     * @param query
     *            统计条件
     */
    public Long getCount(Query query) {
        Selection selection = query.getCriteriaQuery().getSelection();
        query.getCriteriaQuery().select(query.getCriteriaBuilder().count(query.getFrom()));
        Long count = (Long) getEntityManager().createQuery(query.newCriteriaQuery()).getResultList().get(0);
        query.getCriteriaQuery().select(selection);
        return count;
    }

    /**
     * 分页查询
     * 
     * @param query
     *            查询条件
     * @param pageNo
     *            页号
     * @param rowsPerPage
     *            每页显示条数
     */
    public Page queryPage(Query query, int pageNo, int rowsPerPage) {
        if (pageNo <= 0)
            pageNo = 1;
        if (rowsPerPage <= 0)
            rowsPerPage = 7;
        log.debug(query.getClazz() + "-----开始查询,页码:" + pageNo + ",每页显示:" + rowsPerPage + "----");
        log.debug("查询条件:");
        for (Predicate cri : query.getPredicates())
            log.debug(cri);

        int count = getCount(query).intValue();

        // 当把最后一页数据删除以后,页码会停留在最后一个上必须减一
        int totalPageCount = count / rowsPerPage;
        if (pageNo > totalPageCount && (count % rowsPerPage == 0)) {
            pageNo = totalPageCount;
        }
        if (pageNo - totalPageCount > 2) {
            pageNo = totalPageCount + 1;
        }
        int firstResult = (pageNo - 1) * rowsPerPage;
        if (firstResult < 0) {
            firstResult = 0;
        }
        List result = getEntityManager().createQuery(query.newCriteriaQuery()).setFirstResult(firstResult)
                .setMaxResults(rowsPerPage).getResultList();
        return new Page(count, pageNo, rowsPerPage, result);
    }

    /**
     * 根据query查找记录
     * 
     * @param query
     *            查询条件
     * @param firstResult
     *            起始行
     * @param maxResults
     *            结束行
     */
    public <E extends Serializable> List<E> query(Query query, int firstResult, int maxResults) {
        List result = getEntityManager().createQuery(query.newCriteriaQuery()).setFirstResult(firstResult)
                .setMaxResults(maxResults).getResultList();
        return result;
    }

    /**
     * 根据query查找记录
     * 
     * @param query
     *            查询条件
     */
    public <E extends Serializable> List<E> query(Query query) {
        return getEntityManager().createQuery(query.newCriteriaQuery()).getResultList();
    }

    /**
     * 获得主键名称
     * 
     * @param clazz
     *            操作是实体对象
     * @param EntityManager
     *            jpa的entityManager工厂
     * @return 初建名称
     * */
    public static String getIdName(Class clazz, EntityManager entityManager) {
        EntityType entityType = entityManager.getMetamodel().entity(clazz);
        return entityType.getId(entityType.getIdType().getJavaType()).getName();
    }
}

 

IBaseDao接口 

  1. package com.platform.framework.dao.jpa;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5.   
  6. import javax.persistence.EntityManager;  
  7.   
  8. /** 
  9.  * IBaseDao基类<br> 
  10.  *  
  11.  * @describe:系统基础JPA Dao接口 
  12.  */  
  13. @SuppressWarnings({ “rawtypes” })  
  14. public interface IBaseDao {  
  15.       
  16.     public EntityManager getEntityManager();  
  17.   
  18.     public <E> E get(Class clazz, Serializable id);  
  19.   
  20.     /** 
  21.      * 插入记录 
  22.      *  
  23.      * @param entity 
  24.      *            要插入的记录 
  25.      */  
  26.     public void insert(Object entity);  
  27.   
  28.     /** 
  29.      * 更新记录 
  30.      *  
  31.      * @param entity 
  32.      *            要更新的记录 
  33.      */  
  34.     public void update(Object entity);  
  35.   
  36.     /** 更新list */  
  37.     public void updateList(List list);  
  38.   
  39.     /** 
  40.      * 删除记录 
  41.      *  
  42.      * @param entity 
  43.      *            要删除的记录 
  44.      */  
  45.     public void delete(Object entity);  
  46.   
  47.     /** 
  48.      * 删除记录 
  49.      *  
  50.      * @param entity 
  51.      *            要删除的记录 
  52.      */  
  53.     public void delete(Class entity, List ids);  
  54.   
  55.     /** 
  56.      * 删除记录 
  57.      *  
  58.      * @param entity 
  59.      *            要删除的记录 
  60.      */  
  61.     public void delete(Class entity, String jpqlCondition);  
  62.   
  63.     /** 
  64.      * 统计记录 
  65.      *  
  66.      * @param query 
  67.      *            统计条件 
  68.      */  
  69.     public Long getCount(Query query);  
  70.   
  71.     public Long getCount(String jpql);  
  72.   
  73.     /** 
  74.      * 分页查询 
  75.      *  
  76.      * @param query 
  77.      *            查询条件 
  78.      * @param pageNo 
  79.      *            页号 
  80.      * @param rowsPerPage 
  81.      *            每页显示条数 
  82.      */  
  83.     public Page queryPage(Query query, int pageNo, int rowsPerPage);  
  84.   
  85.     /** 
  86.      * 根据query查找记录 
  87.      *  
  88.      * @param query 
  89.      *            查询条件 
  90.      * @param firstResult 
  91.      *            起始行 
  92.      * @param maxResults 
  93.      *            结束行 
  94.      */  
  95.     public <E extends Serializable> List<E> query(Query query, int firstResult, int maxResults);  
  96.   
  97.     /** 
  98.      * 根据query查找记录 
  99.      *  
  100.      * @param query 
  101.      *            查询条件 
  102.      */  
  103.     public <E extends Serializable> List<E> query(Query query);  
  104.   
  105.     /** 
  106.      * 执行更新操作的jpql语句 
  107.      *  
  108.      * @param jpql 
  109.      *            要执行的jpql语句 
  110.      */  
  111.     public <E extends Serializable> List<E> query(String jpql);  
  112.   
  113.     public <E extends Serializable> List<E> queryAll(Class clazz);  
  114.   
  115.     public <E extends Serializable> List<E> query(String jpql, int firstResult, int maxResults);  
  116.   
  117.     /** 
  118.      * 执行查询操作的sql语句 
  119.      *  
  120.      * @param sql 
  121.      *            要执行的sql语句 
  122.      */  
  123.     public <E extends Serializable> List<E> queryBySql(String sql);  
  124.   
  125.     public <E extends Serializable> List<E> queryBySql(String sql, int firstResult, int maxResults);  
  126.   
  127.     /** 
  128.      * 查询记录 
  129.      *  
  130.      * @param clazz 
  131.      *            要查询的实体类 
  132.      * @param hqlCondition 
  133.      *            查询条件 
  134.      */  
  135.     public <E extends Serializable> List<E> query(Class clazz, String hqlCondition);  
  136.   
  137.     /** 
  138.      * 执行更新操作的sql语句 
  139.      *  
  140.      * @param sql 
  141.      *            要执行的sql语句 
  142.      */  
  143.     public Integer updateSql(String sql);  
  144.   
  145.     public Integer updateJpql(String jpql);  
  146.   
  147.     public Page queryPageByJpql(String hql, int pageNo, int rowsPerPage);  
  148.   
  149.     public void updateJpql(String jpql, List paramList);  
  150.   
  151. }  
package com.platform.framework.dao.jpa;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;

/**
 * IBaseDao基类<br>
 * 
 * @describe:系统基础JPA Dao接口
 */
@SuppressWarnings({ "rawtypes" })
public interface IBaseDao {

    public EntityManager getEntityManager();

    public <E> E get(Class clazz, Serializable id);

    /**
     * 插入记录
     * 
     * @param entity
     *            要插入的记录
     */
    public void insert(Object entity);

    /**
     * 更新记录
     * 
     * @param entity
     *            要更新的记录
     */
    public void update(Object entity);

    /** 更新list */
    public void updateList(List list);

    /**
     * 删除记录
     * 
     * @param entity
     *            要删除的记录
     */
    public void delete(Object entity);

    /**
     * 删除记录
     * 
     * @param entity
     *            要删除的记录
     */
    public void delete(Class entity, List ids);

    /**
     * 删除记录
     * 
     * @param entity
     *            要删除的记录
     */
    public void delete(Class entity, String jpqlCondition);

    /**
     * 统计记录
     * 
     * @param query
     *            统计条件
     */
    public Long getCount(Query query);

    public Long getCount(String jpql);

    /**
     * 分页查询
     * 
     * @param query
     *            查询条件
     * @param pageNo
     *            页号
     * @param rowsPerPage
     *            每页显示条数
     */
    public Page queryPage(Query query, int pageNo, int rowsPerPage);

    /**
     * 根据query查找记录
     * 
     * @param query
     *            查询条件
     * @param firstResult
     *            起始行
     * @param maxResults
     *            结束行
     */
    public <E extends Serializable> List<E> query(Query query, int firstResult, int maxResults);

    /**
     * 根据query查找记录
     * 
     * @param query
     *            查询条件
     */
    public <E extends Serializable> List<E> query(Query query);

    /**
     * 执行更新操作的jpql语句
     * 
     * @param jpql
     *            要执行的jpql语句
     */
    public <E extends Serializable> List<E> query(String jpql);

    public <E extends Serializable> List<E> queryAll(Class clazz);

    public <E extends Serializable> List<E> query(String jpql, int firstResult, int maxResults);

    /**
     * 执行查询操作的sql语句
     * 
     * @param sql
     *            要执行的sql语句
     */
    public <E extends Serializable> List<E> queryBySql(String sql);

    public <E extends Serializable> List<E> queryBySql(String sql, int firstResult, int maxResults);

    /**
     * 查询记录
     * 
     * @param clazz
     *            要查询的实体类
     * @param hqlCondition
     *            查询条件
     */
    public <E extends Serializable> List<E> query(Class clazz, String hqlCondition);

    /**
     * 执行更新操作的sql语句
     * 
     * @param sql
     *            要执行的sql语句
     */
    public Integer updateSql(String sql);

    public Integer updateJpql(String jpql);

    public Page queryPageByJpql(String hql, int pageNo, int rowsPerPage);

    public void updateJpql(String jpql, List paramList);

}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页