spring data jpa 多条件查询 + 分页 + 排序
首先自定义Jpa接口类型需要继承接口JpaSpecificationExecutor<T>
下面是实现多条件查询 + 分页 + 排序的代码
导入的的相关类
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification;
public Page<RuleLogInfoDTO> findPageByParam(final QueryRuleLogParam param) {
//分页加排序 Pageable page = PageRequest.of(param.getPageIndex() - 1 , param.getPageSize(),Sort.by(Sort.Order.desc("dateCreate"))); //动态条件 Specification<OperateLogDO> specification = (Specification<OperateLogDO>) (root, query, criteriaBuilder) -> { List<Predicate> list = new ArrayList<>(); if (ObjectUtil.isNotNull(param.getRuleId())){
// 等于查询 list.add(criteriaBuilder.equal(root.get("resourceId"),param.getRuleId())); } if (ObjectUtil.isNotEmpty(param.getRuleName())){
// like查询 list.add(criteriaBuilder.like(root.get("logInfo"),"%" + param.getRuleName()+ "%")); } if (CollectionUtils.isNotEmpty(list)){ Predicate[] p = new Predicate[list.size()]; return criteriaBuilder.and(list.toArray(p)); } return null; };
org.springframework.data.domain.Page<OperateLogDO> pageLogInfo = repository.findAll(specification,page);
return pageLogInfo;
}