JPA 利用javax.persistence.criteria类做复杂查询
作者:互联网
/**
* 数据查询测试
* @param listedType
* @param operatorId
* @param area
* @return
*/
public PagedResponse<Delegation> findAllTest(Integer listedType,String operatorId,String area,Pageable pageable){
Page<Delegation> lists = delegationRepository.findAll(getSerachInfo(listedType,operatorId,area),pageable);
return new PagedResponse<>(lists.getContent(), lists.getNumber(), lists.getSize(), lists.getTotalElements(), lists.getTotalPages(), lists.isLast());
}
public Specification<Delegation> getSerachInfo(Integer listedType,String operatorId,String area){
return new Specification<Delegation>() {
@Override
public Predicate toPredicate(Root<Delegation> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
Join<Delegation,HousingRegistration> join = root.join("housingRegistration",JoinType.INNER);
List<Predicate> predicateList = Lists.newArrayList();
Path<Integer> listedTypePath = root.get("listedType");
if(listedType!=null){
Predicate predicate = criteriaBuilder.equal(listedTypePath,listedType);
predicateList.add(predicate);
}else {
Predicate predicate0 = criteriaBuilder.equal(listedTypePath,0);
Predicate predicate1 = criteriaBuilder.equal(listedTypePath,1);
Predicate predicate = criteriaBuilder.or(predicate0,predicate1);
predicateList.add(predicate);
}
if(StringUtils.isNotBlank(operatorId)){
Path<String> operatorIdPath = root.get("practitionersId");
Predicate predicate = criteriaBuilder.equal(operatorIdPath,operatorId);
predicateList.add(predicate);
}
if(StringUtils.isNotBlank(area)){
Path<String> areaPath = join.get("area");
Predicate predicate = criteriaBuilder.equal(areaPath,area);
predicateList.add(predicate);
}
Predicate predicateResult = null;
if(predicateList!=null && predicateList.size()>0){
for(Predicate predicate:predicateList){
if(predicateResult==null){
predicateResult = predicate;
}else {
predicateResult = criteriaBuilder.and(predicateResult,predicate);
}
}
}
return predicateResult;
}
};
}
标签:predicate,JPA,criteriaBuilder,Predicate,lists,listedType,predicateList,criteria, 来源: https://blog.csdn.net/yssa1125001/article/details/89927037