findAll(Pageable) returns 排序顺序错误

findAll(Pageable) returns wrong sorting order

为什么 PagingAndSortingRepository<City, Long> return 方法 findAll(Pageable) 之后的排序顺序错误? 在服务层我有这个方法,我试图按人口排序:

    public Set<City> findAllPageable(int page, int size, String sortBy) {
        Pageable paging = PageRequest.of(page, size, Sort.by(sortBy));
        return new HashSet<>(repository.findAll(paging).getContent());
    }

这是我期望看到的:

    select Population from city order by Population limit 10;
42
167
300
455
503
559
595
682
700
800

这是迭代 Set<City>:

后的实际结果
682, 42, 300, 700, 559, 595, 800, 167, 455, 503

所有这些数字都是正确的,但顺序不正确。为什么?

您不能依赖 HashSet 中返回的订单元素。如果你必须在那里使用一个集合,使用一个LinkedHashSet,它保证顺序:

return new LinkedHashSet<>(repository.findAll(paging).getContent());

returned HashSet 实现不维护城市的排序

使用 TreeSet 实现并传递 Comparator<City> 或让 City 实现 Copmarable<City>。在这种情况下,我还建议您 return SortedSet<City>

The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

public SortedSet<City> findAllPageable(int page, int size, String sortBy) {
     Pageable paging = PageRequest.of(page, size, Sort.by(sortBy));
     return new TreeSet<>(
         repository.findAll(paging).getContent(), 
         Comparator.comparing(City::getPopulation));
}