Spring Data JPA,一种动态条件查询的写法

咱们在使用SpringData JPA框架时,进行条件查询,若是是固定条件的查询,咱们能够使用符合框架规则的自定义方法以及@Query注解实现。spring

若是是查询条件是动态的,框架也提供了查询接口。express

JpaSpecificationExecutor

 和其余接口使用方式同样,只须要在你的Dao接口继承便可(官网代码)。框架

public interface CustomerRepository extends CrudRepository<Customer, Long>, JpaSpecificationExecutor {
 …
}

JpaSpecificationExecutor提供不少条件查询方法。less

public interface JpaSpecificationExecutor<T> {
    T findOne(Specification<T> var1);

    List<T> findAll(Specification<T> var1);

    Page<T> findAll(Specification<T> var1, Pageable var2);

    List<T> findAll(Specification<T> var1, Sort var2);

    long count(Specification<T> var1);
}

好比方法:dom

List<T> findAll(Specification<T> var1);

就能够查找出符合条件的全部数据,若是你的框架使用的是前段分页的技术,那么这个方法就挺简便的。ide

那么这个方法该如何使用呢?咱们看到它须要的参数是一个ui

org.springframework.data.jpa.domain.Specification

对象。那咱们就建立这个对象先看看。this

Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                return null;
            }
        }

IDE自动生成了要重写的方法toPredicate。spa

root参数是咱们用来对应实体的信息的。criteriaBuilder能够帮助咱们制做查询信息。rest

/**
 * A root type in the from clause.
 * Query roots always reference entities.
 *
 * @param <X> the entity type referenced by the root
 * @since Java Persistence 2.0
 */
public interface Root<X> extends From<X, X> {...}
/**
 * Used to construct criteria queries, compound selections,
 * expressions, predicates, orderings.
 *
 * <p> Note that <code>Predicate</code> is used instead of <code>Expression&#060;Boolean&#062;</code>
 * in this API in order to work around the fact that Java
 * generics are not compatible with varags.
 *
 * @since Java Persistence 2.0
 */
public interface CriteriaBuilder {...}

CriteriaBuilder对象里有不少条件方法,好比制定条件:某条数据的建立日期小于今天。

criteriaBuilder.lessThan(root.get("createDate"), today)

该方法返回的对象类型是Predicate。正是toPredicate须要返回的值。

若是有多个条件,咱们就能够建立一个Predicate集合,最后用CriteriaBuilder的and和or方法进行组合,获得最后的Predicate对象。

 

/**
     * Create a conjunction of the given restriction predicates.
     * A conjunction of zero predicates is true.
     *
     * @param restrictions zero or more restriction predicates
     *
     * @return and predicate
     */
    Predicate and(Predicate... restrictions);
/**
     * Create a disjunction of the given restriction predicates.
     * A disjunction of zero predicates is false.
     *
     * @param restrictions zero or more restriction predicates
     *
     * @return or predicate
     */
    Predicate or(Predicate... restrictions);

示例:

public List<WeChatGzUserInfoEntity> findByCondition(Date minDate, Date maxDate, String nickname){
        List<WeChatGzUserInfoEntity> resultList = null;
        Specification querySpecifi = new Specification<WeChatGzUserInfoEntity>() {
            @Override
            public Predicate toPredicate(Root<WeChatGzUserInfoEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                List<Predicate> predicates = new ArrayList<>();
                if(null != minDate){
                    predicates.add(criteriaBuilder.greaterThan(root.get("subscribeTime"), minDate));
                }
                if(null != maxDate){
                    predicates.add(criteriaBuilder.lessThan(root.get("subscribeTime"), maxDate));
                }
                if(null != nickname){
                    predicates.add(criteriaBuilder.like(root.get("nickname"), "%"+nickname+"%"));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        resultList =  this.weChatGzUserInfoRepository.findAll(querySpecifi);
        return resultList;
    }

and到一块儿的话全部条件就是且关系,or就是或关系了。

其实也是在Stack Overflow上看到的。

相关文章
相关标签/搜索