spring-data-jpa Specification構建動態ql

flyingkid發表於2018-12-01

1.持久層繼承JpaSpecificationExecutor

@Repository
public interface DailyBillingRepository extends PagingAndSortingRepository<DailyBilling, Long>, JpaSpecificationExecutor<DailyBilling> {

}
複製程式碼

2.JpaSpecificationExecutor 提供的方法:

public interface JpaSpecificationExecutor<T> {
 
    T findOne(Specification<T> spec);
 
    List<T> findAll(Specification<T> spec);
 
    Page<T> findAll(Specification<T> spec, Pageable pageable);
 
    List<T> findAll(Specification<T> spec, Sort sort);
 
    long count(Specification<T> spec);
}
複製程式碼

呼叫 :

 public Page<DailyBilling> getList(Integer page, Integer rows,String beginTime,String endTime,String result){
        //Specification建立動態sql
        //Root<ExportSubsidyPersonnel> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder
        Specification<DailyBilling> specification= (root, query, cb) -> {
            Predicate predicate = cb.conjunction();
 
            if (StringHelper.isNotBlank(beginTime) && StringHelper.isNotBlank(endTime)){
                // sql ==》 billData between beginTime and endTime
                predicate.getExpressions().add(
                        cb.between(root.<Date>get("billData"), DateHelper.getDate(beginTime), DateHelper.getDate(endTime))
                );
            }
 
            if (StringHelper.isNotBlank(result) && !result.equals("2")){
                // sql ==》 differenceAmount = 0  或者 differenceAmount <> 0
                Predicate p = null;
                if ("1".equals(result)){
                    p = cb.equal(root.<BigDecimal>get("differenceAmount"),BigDecimal.ZERO);
                }
                if ("0".equals(result)){
                    p = cb.notEqual(root.<BigDecimal>get("differenceAmount"),BigDecimal.ZERO);
                }
                predicate.getExpressions().add(p);
            }
            return predicate;
        };
 
        return dailyBillingRepository.findAll(specification,new PageRequest(page,rows));
    }
複製程式碼

CriteriaBuilder介面提供了操作sql的基本語句,可直接呼叫。

相關文章