Spring Data Pageable破坏了Spring Data JPA的OrderBy功能

3

我有一个简单的JpaRepository,其中有一个查找器,按照名为“number”的属性降序返回记录。 “number”属性也是我的实体的@Id。 这很好用,但是有成千上万条记录,所以我想返回一个页面而不是一个列表。

@Repository
public interface ReceiptRepository extends JpaRepository<Receipt, BigDecimal> {

    @Query
    public List<Receipt> findByStorerOrderByNumberDesc(String storer);
}

如果我将我的查找器更改为以下内容,排序就不再起作用了。我尝试使用Pageable参数的排序功能,但它没有起作用。也删除了OrderByNumberDesc,但结果相同。
@Repository
public interface ReceiptRepository extends JpaRepository<Receipt, BigDecimal> {

    @Query
    public Page<Receipt> findByStorerOrderByNumberDesc(String storer, Pageable pageable);
}

编辑 - 添加控制器方法

以下是我的控制器方法。

@RequestMapping(method = RequestMethod.GET, produces = {"application/json"})
public PagedResources<Receipt> receipts(Pageable pageable, PagedResourcesAssembler assembler) {
    Page<Receipt> receipts = receiptRepository.findByStorer("003845", pageable);
    return assembler.toResource(receipts, receiptResourceAssembler);
}

我感觉我在这里缺少了一些非常基础的东西。

我正在使用Spring Data JPA 1.5.2和Commons 1.7.2。

谢谢:)

1个回答

12
在创建Pageable时,将排序添加到其中:
例如:
Pageable pageable ...;
pageable.getSort().and(new Sort(Direction.ASC, "prop1", "prop1"));

在Spring MVC中,您可以这样做:

@RequestMapping(method = RequestMethod.GET, produces = {"application/json"})
public PagedResources<Receipt> receipts(@PageableDefaults(sort = { "x",
            "y", "z" }, value = 10)Pageable pageable, PagedResourcesAssembler assembler) {
    Page<Receipt> receipts = receiptRepository.findByStorer("003845", pageable);
    return assembler.toResource(receipts, receiptResourceAssembler);
}

你已经有一个可分页的对象,所以只需按照上述方法操作即可。 - Alan Hay
2
查询参数以"?page=0&size=20&sort=number,desc"的形式传入,这将被转换为一个Pageable对象,其中page=0,size=20,sort属性按照"number"属性降序排列。因此,我不需要修改Pageable对象,它已经包含了我想要的内容。问题在于它并没有起作用。 - Patrick Grimard
只有在您点击链接进行排序后,它才会起作用。如果您没有指定默认值或添加排序,则初始排序将是错误的。请参见更新的答案。 - Alan Hay
如果您的方法仍然被称为findByStorerOrderByNumberDesc(),那么它将会无论Pageable正在做什么。 - Alan Hay
粘贴生成的SQL。 - Alan Hay
显示剩余8条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接