Spring Boot CrudRepository 或 JpaRepository - 如何将限制作为参数传递? [英] Spring Boot CrudRepository or JpaRepository - how to pass limit as argument?

查看:18
本文介绍了Spring Boot CrudRepository 或 JpaRepository - 如何将限制作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有扩展 CrudRepository 的存储库接口:

I have repository interface which extends CrudRepository:

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

我想将结果列表限制为指定的限制,就像 SQL 查询中的 limit 一样.

I want to limit list of results to a specified limit like with limit in SQL query.

但是我得到:

引起:org.springframework.beans.factory.BeanCreationException:创建名为exampleRepository"的 bean 时出错:调用 init方法失败;嵌套异常是 java.lang.IllegalArgumentException:未能创建查询方法 public abstract 找不到属性限制类型

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'exampleRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query method public abstract No property limit found for type

如何将限制作为参数传递给 CrudRepository 方法?

How to add limit passed as argument to CrudRepository method?

推荐答案

来自 spring doc (限制查询结果):

From spring doc (Limiting query results):

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

The results of query methods can be limited via the keywords first or top, which can be used interchangeably. An optional numeric value can be appended to top/first to specify the maximum result size to be returned. If the number is left out, a result size of 1 is assumed.

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

So, for fixed limit N you can use List<Example> findTopNByValidIsTrue()

对于限制的变量值,您应该使用 可分页:

For variable value of limit you should use Pageable:

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

这篇关于Spring Boot CrudRepository 或 JpaRepository - 如何将限制作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆