spring 为 JPA Pageable Object 设置默认页面大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27032433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set default page size for JPA Pageable Object
提问by Kousick Shanmugam Nagaraj
I have a PagingandSorting Repository which has a method that accecpts a pageable object. I also have a controller that accepts a pageable object through the URL.
我有一个 PagingandSorting Repository,它有一个接受可分页对象的方法。我还有一个通过 URL 接受可分页对象的控制器。
My use case is that, if a user specifies a page size parameter in the URL i must take that value for the pageable object. If he does not mention take a default value of 50.
我的用例是,如果用户在 URL 中指定页面大小参数,我必须为可分页对象采用该值。如果他不提及,则采用默认值 50。
But the pageable object defaults to 20 right now.
但是 pageable 对象现在默认为 20。
Any Suggestions would help
任何建议都会有所帮助
回答by Alan Hay
If you are talking about a Spring Data PagingAndSortingRepository you can set the default page size by using the @PageableDefaulton a Controller method as follows:
如果您正在谈论 Spring Data PagingAndSortingRepository,您可以使用@PageableDefault控制器方法设置默认页面大小,如下所示:
public String listClients(@ModelAttribute FilterForm form, Model model, WebRequest request, @PageableDefault(sort = { "surname",
"forename", "address.town" }, value = 50) Pageable pageable) {
}
Or you can configure a global default using the following in your Spring config as shown below in both XML and Java config.
或者,您可以在 Spring 配置中使用以下内容配置全局默认值,如下面的 XML 和 Java 配置所示。
Note that newer versions of Spring Data use zero based page indexing while older versions used 1 for the first page. If your UI paging library expects 1 as first page then you can set the oneIndexedParametersproperty to true:
请注意,较新版本的 Spring Data 使用基于零的页面索引,而旧版本使用 1 作为第一页。如果您的 UI 分页库期望 1 作为第一页,那么您可以将该oneIndexedParameters属性设置为true:
Configures whether to expose and assume 1-based page number indexes in the request parameters. Defaults to false, meaning a page number of 0 in the request equals the first page. If this is set to true, a page number of 1 in the request will be considered the first page.
Parameters: oneIndexedParameters - the oneIndexedParameters to set
配置是否在请求参数中公开和假设基于 1 的页码索引。默认为 false,意味着请求中的页码 0 等于第一页。如果设置为 true,则请求中的页码 1 将被视为第一页。
参数: oneIndexedParameters - 要设置的 oneIndexedParameters
Configures the Pageable to be used as fallback in case no PageableDefault or PageableDefaults (the latter only supported in legacy mode) can be found at the method parameter to be resolved. If you set this to null, be aware that you controller methods will get null handed into them in case no Pageable data can be found in the request. Note, that doing so will require you supply bot the page and the size parameter with the requests as there will be no default for any of the parameters available.
Parameters: fallbackPageable - the Pageable to be used as general fallback.
如果在要解析的方法参数中找不到 PageableDefault 或 PageableDefaults(后者仅在传统模式下支持),则将 Pageable 配置为用作回退。如果将此设置为 null,请注意,如果在请求中找不到 Pageable 数据,您的控制器方法将获得 null 传递给它们。请注意,这样做将要求您为请求提供页面和大小参数,因为任何可用参数都没有默认值。
参数: fallbackPageable - 用作一般后备的 Pageable。
In XML this looks like the following then:
在 XML 中,这看起来如下所示:
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="org.springframework.data.web.PageableHandlerMethodArgumentResolver">
<property name="oneIndexedParameters" value="true"/>
<property name="fallbackPageable">
<bean class="org.springframework.data.domain.PageRequest">
<constructor-arg name="page" value="1" />
<constructor-arg name="size" value="10" />
</bean>
</property>
</bean>
</mvc:argument-resolvers>
</mvc:annotation-driven>
In Java Config this looks like the below:
在 Java Config 中,如下所示:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver();
resolver.setOneIndexedParameters(true);
resolver.setFallbackPageable(new PageRequest(1, 20));
argumentResolvers.add(resolver);
super.addArgumentResolvers(argumentResolvers);
}
}
回答by Przemek Nowak
For Spring Boot 2.X you have set of parameters:
对于 Spring Boot 2.X,您有一组参数:
# DATA WEB (SpringDataWebProperties)
spring.data.web.pageable.default-page-size=20 # Default page size.
spring.data.web.pageable.max-page-size=2000 # Maximum page size to be accepted.
spring.data.web.pageable.one-indexed-parameters=false # Whether to expose and assume 1-based page number indexes.
spring.data.web.pageable.page-parameter=page # Page index parameter name.
spring.data.web.pageable.prefix= # General prefix to be prepended to the page number and page size parameters.
spring.data.web.pageable.qualifier-delimiter=_ # Delimiter to be used between the qualifier and the actual page number and size properties.
spring.data.web.pageable.size-parameter=size # Page size parameter name.
spring.data.web.sort.sort-parameter=sort # Sort parameter name.
回答by Sathish Kumar Thiyagarajan
You can set below in application.yml
您可以在 application.yml 下面设置
spring.data.rest.default-page-size: 50
回答by Rori Stumpf
And, for completeness, here is an example for a Spring Boot configuration. In the @Configuration class that extends WebMvcConfigurerAdapter, set the default page size to 50 items like this:
而且,为了完整起见,这里有一个 Spring Boot 配置示例。在扩展 WebMvcConfigurerAdapter 的 @Configuration 类中,将默认页面大小设置为 50 项,如下所示:
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver();
resolver.setFallbackPageable(new PageRequest(0, 50));
argumentResolvers.add(resolver);
super.addArgumentResolvers(argumentResolvers);
}
回答by Hadi hashemi
You can use this Annotation before your Pageable param:
您可以在 Pageable 参数之前使用此注释:
@PageableDefault(size = 40)
// so your parameter should be like this:
@PageableDefault(size = 40) Pageable pageable
** Update: You can store 40 in application.yml file and use it in the whole project.
** 更新:您可以在 application.yml 文件中存储 40 并在整个项目中使用它。
in application.yml :
在 application.yml 中:
pageSize: 40
then:
然后:
// so your parameter should be like this:
@PageableDefault(size = ${pageSize}) Pageable pageable
回答by Ash_P
In Spring Boot 2.1.6.RELEASE, you can use below:
在 Spring Boot 中2.1.6.RELEASE,您可以在下面使用:
@Configuration
public class WebConfig implements WebMvcConfigurer{
@Value("${paging.default.pageSize}")
private int size;
@Value("${paging.default.page}")
private int page;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver();
resolver.setFallbackPageable(PageRequest.of(page, size));
resolvers.add(resolver);
WebMvcConfigurer.super.addArgumentResolvers(resolvers);
}
}
回答by jasondt
This still isn't well documented but for anyone else finding this article, the RepositoryRestConfigurerAdapter has all the spring data rest config there.
这仍然没有很好的记录,但是对于找到这篇文章的其他人来说, RepositoryRestConfigurerAdapter 那里有所有的 spring 数据休息配置。
@Configuration
public static class RestConfig extends RepositoryRestConfigurerAdapter {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setDefaultPageSize(50);
}
}
回答by Tom
Provided answers are very good and should help in most cases. However, I use slightly different approach, which allows me to use different default page size per model and can be configurable with Spring or system properties.
提供的答案非常好,在大多数情况下应该会有所帮助。但是,我使用了稍微不同的方法,它允许我为每个模型使用不同的默认页面大小,并且可以使用 Spring 或系统属性进行配置。
Please note that this approach has one fundamental limitation, namely, it does not accept any size coming with a request; it uses sorting information though. So if you need ability to change number of returned items per page via request parameters, this solution is not for you.
请注意,这种方法有一个基本限制,即它不接受任何大小的请求;虽然它使用排序信息。因此,如果您需要通过请求参数更改每页返回项目的数量,则此解决方案不适合您。
First of all, I created a utility class (or just a method in a controller) which creates a new Pageableinstance base on a request Pageableand configured page size
首先,我创建了一个实用程序类(或只是控制器中的一个方法),它根据Pageable请求Pageable和配置的页面大小创建一个新实例
public static Pageable updatePageable(final Pageable source, final int size)
{
return new PageRequest(source.getPageNumber(), size, source.getSort());
}
In a controller I add a variable which holds my default page size (in this case default value is 20 if configuration is not provided):
在控制器中,我添加了一个变量来保存我的默认页面大小(在这种情况下,如果未提供配置,则默认值为 20):
@Value("${myapplication.model.items-per-page:20}")
private int itemsPerPage;
And then I override(i.e. create a new Pageableinstance) default page size in request handling method:
然后我在请求处理方法中覆盖(即创建一个新Pageable实例)默认页面大小:
@RequestMapping(method = RequestMethod.GET)
public Page<Model> websites(final Pageable pageable)
{
return repository.findAll(updatePageable(pageable, itemsPerPage));
}
I use different default page size variables for different models / controllers which then can be configured even from system properties.
我为不同的模型/控制器使用不同的默认页面大小变量,然后甚至可以从系统属性进行配置。

