Spring Boot CrudRepository或JpaRepository - 如何将限制作为参数传递?

3

我有一个仓库接口,它扩展了CrudRepository

public interface ExampleRepository extends CrudRepository<Example, Long>{
    List<Example> findByValidIsTrueLimit(Integer limit);
}

我想限制结果列表的数量,就像在 SQL 查询中使用 limit 一样。但是我遇到了以下问题:

由于 org.springframework.beans.factory.BeanCreationException 错误导致无法创建名为 “exampleRepository” 的 Bean:初始化方法调用失败;嵌套异常为 java.lang.IllegalArgumentException:未找到类型为 limit 的属性。

如何将作为参数传递的 limit 添加到 CrudRepository 方法中?
3个回答

2

来自Spring文档(限制查询结果):

查询方法的结果可以通过关键字first或top进行限制,这两个关键字可以互换使用。可将一个可选的数字值附加到top/first以指定要返回的最大结果大小。如果省略了数字,则假定结果大小为1。

因此,对于固定限制N,您可以使用List<Example> findTopNByValidIsTrue()

对于限制值的可变性,应使用Pageable:

Page<Example> findByValidIsTrue(Pageable pageable);
List<Example> result = repository.findByValidIsTrue(new PageRequest(0, N)).getContent();

不需要使用getContent(),你可以直接获取List<Example>。 - Justinas Jakavonis

2
您可以使用Pageable,它将为您提供一个Page<T>,然后您可以从中获取所请求的数据。
 Page<Example> findByValidIsTrue(Pageable pageable);

然后使用PageRequest调用它:

    PageRequest req = new PageRequest(0,10); // I just want 10 record
    Page<Example> page =  findByValidIsTrue(req )
    List<Example> nRecords = page.getContent();

注意:如果在调用findByValidIsTrueLimit时没有传递PageRequest对象,则默认返回前20条记录。

不需要使用getContent(),你可以直接获取List<Example>。 - Justinas Jakavonis

1
你可以在方法签名中添加Pageable。例如:

List<Example> findByValidIsTrue(Pageable p);

用法:

List<Example> ex = repo.findByValidIsTrue(new PageRequest(0, 10));


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