jpa用findAll((Specification<GoodsSpu>) (root, criteriaQuery, criteriaBuilder) -> {})排序

//需要用到的包
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;


//findAll查询
Sort s = Sort.by(Sort.Direction.DESC, "updatedTime");//更新时间倒序排序
Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, s);//排序规则放到pageable中
Page<Goods> page = goodsRepository.findAll((Specification<Goods>) (root, criteriaQuery, criteriaBuilder) -> {
  List<Predicate> list = Lists.newArrayList();
  list.add(criteriaBuilder.notEqual(root.get("del"), Goods.Del.YES.getCode()));
  Predicate[] arr = new Predicate[list.size()];
  
criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createdTime")));//根据创建时间倒叙排序,注意这种排休会被pageable的排序给覆盖掉
  criteriaQuery.where(list.toArray(arr));
  return criteriaQuery.getRestriction();
},
pageable);//注意这里使用了pageable不管pageable有没有设置排序都会覆盖掉criteriaQuery.orderBy()的排序,如果pageable没有设置排序那结果就是无序的

 

posted @ 2022-06-28 09:59  llili  阅读(1976)  评论(0编辑  收藏  举报