根据接收参数值进行应排序字段动态匹配 实现排序自动切换
核心代码
@Override
@Transactional(readOnly = true)
public Results<Spu> list(final Integer cid, final Integer gid, final String name, final Integer sign, final Integer flag, final Integer sort, final Integer type, final String dtStart, final String dtEnd, final Integer cur, final Integer page) {
String pro;
switch (sort) {
case 1:
pro = "min";
break;
case 2:
pro = "sal";
break;
default:
pro = "id";
break;
}
Sort.Direction direction;
if (type == 1) {
direction = Sort.Direction.ASC;
} else {
direction = Sort.Direction.DESC;
}
log.info("direction:{},pro:{}", direction, pro);
Pageable pageable = PageRequest.of(cur, page, direction, pro);
Page<Spu> lst = spuRepository.findAll((Specification<Spu>) (root, query, cb) -> {
List<Predicate> list = new ArrayList<>();
if (VerificationUtil.isNotNull(cid)) {
list.add(cb.equal(root.get("cid").as(Integer.class), cid));
}
if (VerificationUtil.isNotNull(gid)) {
list.add(cb.equal(root.get("gid").as(Integer.class), gid));
}
if (StringUtils.isNotBlank(name)) {
list.add(cb.like(root.get("name").as(String.class), "%" + name + "%"));
}
if (VerificationUtil.isNotNull(sign)) {
list.add(cb.equal(root.get("sign").as(Integer.class), sign));
}
if (VerificationUtil.isNotNull(flag)) {
list.add(cb.equal(root.get("flag").as(Integer.class), flag));
}
return BaseService.getPredicate(dtStart, dtEnd, cb, list, root.get("createTime"));
}, pageable);
return new Results<>(lst.getContent(), lst.getSize(), lst.getTotalElements(), lst.getNumber(), lst.getTotalPages());
}