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上看到的。

相關文章
相關標籤/搜索