gpt4 book ai didi

spring - 为 JPA 可分页对象设置默认页面大小

转载 作者:IT老高 更新时间:2023-10-28 13:51:06 24 4
gpt4 key购买 nike

我有一个 PagingandSorting Repository,它有一个接受可分页对象的方法。我还有一个通过 URL 接受可分页对象的 Controller 。

我的用例是,如果用户在 URL 中指定页面大小参数,我必须将该值用于可分页对象。如果他不提取默认值50。

但可分页对象现在默认为 20。

任何建议都会有所帮助

最佳答案

如果您谈论的是 Spring Data PagingAndSortingRepository,您可以通过在 Controller 方法上使用 @PageableDefault 来设置默认页面大小,如下所示:

public String listClients(@ModelAttribute FilterForm form, Model model, WebRequest request, @PageableDefault(sort = { "surname",
"forename", "address.town" }, value = 50) Pageable pageable) {

}

或者您可以在 Spring 配置中使用以下内容配置全局默认值,如下面的 XML 和 Java 配置所示。

请注意,较新版本的 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

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.

在 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>

在 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);
}
}

关于spring - 为 JPA 可分页对象设置默认页面大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27032433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com