Java Spring 数据:按 ID Desc 排序

Java Spring Data : Sort By ID Desc

我只想按 ID 后代对我的数据进行排序,但我不知道该怎么做,这是我在服务层中的代码

public Page<Facture> selectByPage(Pageable p) {
    Page<Facture> pagedResult = factureRepository.findAll(p);
    return pagedResult;
}

您可以使用Sort.of(...).descending()按字段降序排列。

public Page<Facture> selectByPage(Pageable p) {
    // Here, replace "id" with your field name that refers to id.
    Pageable pSort = PageRequest.of(p.getPageNumber(), p.getPageSize(), Sort.by("id").descending());
    
    Page<Facture> pagedResult = factureRepository.findAll(pSort);
    return pagedResult;
}

带有数据 JPA 规范的简单示例:

Sort sort = Sort.by(Sort.Direction.DESC, "id");
Pageable pageable = PageRequest.of(pageNo, pageSize, sort);
Specification specification = simpleSearchSpecification(bcpConsumerVo, bcpUserVo);
Page<BcpConsumer> bcpConsumers = bcpConsumerRepository.findAll(specification, pageable);

simpleSearchSpecification方法:

 private Specification simpleSearchSpecification(BcpConsumerVo bcpConsumerVo, BcpUserVo bcpUserVo) {
        return (Specification<BcpConsumer>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<>(6);
            List<Predicate> orList = new ArrayList<>();
            if (Boolean.FALSE.equals(bcpUserVo.isAdmin())) {
                predicateList.add(criteriaBuilder.equal(root.get("owner"), bcpUserVo.getId()));
            }
            if (!StringUtils.isEmpty(bcpConsumerVo.getName())) {
                orList.add(criteriaBuilder.like(root.get("name"), "%" + bcpConsumerVo.getName() + "%"));
                orList.add(criteriaBuilder.like(root.get("authKey"), "%" + bcpConsumerVo.getName() + "%"));
            }
            predicateList.add(criteriaBuilder.or(orList.toArray(new Predicate[0])));
            return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
        };
    }