spring-data-jpa Specification構建動態sql
阿新 • • 發佈:2019-01-04
1.持久層繼承JpaSpecificationExecutor<T>
@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的基本語句,可直接呼叫。