Java spring data jpa 限制pagesize,如何设置为maxSize

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23751193/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:00:52  来源:igfitidea点击:

spring data jpa limit pagesize, how to set to maxSize

javaspring-data-jpa

提问by Awakening

I have one requirement is to search by pageable and non-pageable,

我有一个要求是按可分页和不可分页进行搜索,

and in my Java code, I use spring data jpa Pageable class,

在我的 Java 代码中,我使用 spring 数据 jpa Pageable 类,

 Pageable pageable = new PageRequest(
                    queryForm.getPageNumber()- 1, queryForm.getPageSize(),Sort.Direction.ASC,"id");  
Page page = repository.fullTextSearch(queryForm.getText(), pageable);

And I don't want to change the return structure,

我不想改变回报结构,

So when non-pageable situation (search all), how to set the pageSize value to MAX ?

那么当不可分页的情况下(搜索全部),如何将 pageSize 值设置为 MAX ?

采纳答案by Kamill Sokol

In conjunction with Spring MVC you can use PageableDefaultsannotation with value = Integer.MAX_VALUElike

与 Spring MVC 结合使用,您可以使用类似的PageableDefaults注解value = Integer.MAX_VALUE

public String showUsers(Model model, 
  @PageableDefaults(pageNumber = 0, value = Integer.MAX_VALUE) Pageable pageable) { … }

see PageableDefaults annotationJavadoc.

请参阅PageableDefaults 注释Javadoc。

In any other client code you can set second constructor parameter to Integer.MAX_VALUE:

在任何其他客户端代码中,您可以将第二个构造函数参数设置为Integer.MAX_VALUE

new PageRequest(
    queryForm.getPageNumber()- 1, 
    queryForm.getPageSize() == null ? Integer.MAX_VALUE : queryForm.getPageSize(),
    Sort.Direction.ASC,"id"); 

see PageRequest constructor. I assume that queryForm.getPageSize()is a wrapper type not a primitive. Otherwise you get a zero if pageSize wasn't set by the user (intentionally for a "search all" request).

请参阅PageRequest 构造函数。我假设这queryForm.getPageSize()是一个包装类型而不是原始类型。否则,如果用户未设置 pageSize(有意用于“搜索全部”请求),则会得到零。

UPDATE:

更新:

Since Spring Data Commons 1.6 you should use PageableDefaultinstead of PageableDefaults

从 Spring Data Commons 1.6 开始,您应该使用PageableDefault而不是PageableDefaults

public String showUsers(Model model, 
    @PageableDefault(page= 2 ,value = Integer.MAX_VALUE)

See PageableDefault annotationJavadoc.

请参阅PageableDefault 注释Javadoc。

回答by user3805618

This works for me:

这对我有用:

All pageable request use MyCustomPageand use a default page and size if not found in request.

MyCustomPage如果在请求中未找到,所有可分页请求都使用并使用默认页面和大小。

If size (number of record exceed the max value) i set a default value, which in this case 50.

如果大小(记录数超过最大值)我设置一个默认值,在这种情况下是 50。

public class MyCustomPage extends PageRequest{
    Integer MAX_PAGE_SIZE = 50
    //constructor 
    public MyCustomPage(Integer page, Integer size) {
        super(page,(size>MAX_PAGE_SIZE)?MAX_PAGE_SIZE:size);
    }
}

回答by luke

If you use Spring MVC this may help you. According to comments below this answer is fully correct for Spring 4.x.x and maybe ealier, but for Spring 5.x.x you probably need another solution.

如果您使用 Spring MVC,这可能对您有所帮助。根据下面的评论,这个答案对于 Spring 4.xx 是完全正确的,也许更准确,但对于 Spring 5.xx,您可能需要另一个解决方案。

The first thing that you have to do is to use @PageableDefaultannotation and set size to Integer.MAX_VALUE or any other value you want:

您要做的第一件事是使用@PageableDefault注释并将大小设置为 Integer.MAX_VALUE 或您想要的任何其他值:

public SomeResponseObject getSomething(
    @PageableDefault(size = Integer.MAX_VALUE) Pageable page
) {
    return someService.getSomething(page);
}

But it is not enough when your size value is very big (bigger than 2000 in Spring Data Core/spring-data-commons 1.12.3), because size will be still limited by maxPageSizevariable in PageableHandlerMethodArgumentResolverclass which is set by default to 2000. This was mentioned by pdorgambide. You will get something like this:
Response with size limited to 2000 because of default maxPageSize
As you can see there is size=2000 instead of expected size=2147483647 (size=Integer.MAX_VALUE).
So the second step is to change mentioned maxPageSize. We can do it by overriding PageableHandlerMethodArgumentResolver. One of the ways to do it is to create a proper java configuration file in a proper package - if you use such kind of configuration in your project. You can do it also in xml config file if your project uses such. There is my solution (Java Spring Configuration File):

但是当你的 size 值非常大(在 Spring Data Core/spring-data-commons 中大于 2000)时,这还不够1.12.3,因为 size 仍然受到类中maxPageSize变量的限制PageableHandlerMethodArgumentResolver,默认设置为 2000。这是由吡多甘胺。你会得到这样的结果: 如你所见,size=2000 而不是预期的 size=2147483647 (size=Integer.MAX_VALUE)。 所以第二步就是改提。我们可以通过覆盖. 一种方法是在适当的包中创建适当的 java 配置文件 - 如果您在项目中使用这种配置。如果您的项目使用这样的配置,您也可以在 xml 配置文件中执行此操作。有我的解决方案(Java Spring 配置文件):
由于默认 maxPageSize,响应大小限制为 2000

maxPageSizePageableHandlerMethodArgumentResolver

@Configuration
@EnableConfigurationProperties
public class PaginationConfiguration extends SpringDataWebConfiguration {

    @Bean
    public PageableHandlerMethodArgumentResolver pageableResolver() {
        PageableHandlerMethodArgumentResolver pageableHandlerMethodArgumentResolver =
            new PageableHandlerMethodArgumentResolver(sortResolver());

        pageableHandlerMethodArgumentResolver.setMaxPageSize(Integer.MAX_VALUE);

        return pageableHandlerMethodArgumentResolver;
    }

}

Now everything works as expected:
Response with proper size equal to Integer.MAX_VALUE which is 2147483647

现在一切都按预期工作:
正确大小的响应等于 Integer.MAX_VALUE,即 2147483647

It is also worth to mention that in @PageableDefaultannotation valueis equivalent to size. In other words it is alias for size. It means that instead of size=Integer.MAX_VALUEyou can write value=Integer.MAX_VALUE. What is more althought it makes no sense you can use both in the same time. If they are different only sizeis taken into consideration.

还值得一提的是, in@PageableDefault注释value相当于size. 换句话说,它是 的别名size。这意味着size=Integer.MAX_VALUE你可以写value=Integer.MAX_VALUE. 更重要的是,您可以同时使用两者是没有意义的。如果它们不同,则仅size考虑。

回答by varren

If you need per-controller limits like this:

如果您需要这样的每个控制器限制:

@RequestMapping(path = "/users")
public ModelAndView users(@PageableLimits(maxSize = 10) Pageable pageable) {
    ...
}

@RequestMapping(path = "/comments")
public ModelAndView comments(@PageableLimits(maxSize = 100) Pageable pageable) {
    ...
}

It can be done with custom annotation:

它可以通过自定义注释来完成:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface PageableLimits {
    int maxSize() default Integer.MAX_VALUE;

    int minSize() default 0;
}

And extended PageableHandlerMethodArgumentResolverconfiguration:

和扩展PageableHandlerMethodArgumentResolver配置:

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver() {

            @Override
            public Pageable resolveArgument(MethodParameter methodParameter, @Nullable ModelAndViewContainer mavContainer,
                                            NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) {
                Pageable p = super.resolveArgument(methodParameter, mavContainer, webRequest, binderFactory);
                return getLimitsFromAnnotation(p, methodParameter);
            }

            private Pageable getLimitsFromAnnotation(Pageable p, MethodParameter methodParameter) {

                PageableLimits limits = methodParameter.getParameterAnnotation(PageableLimits.class);

                if (limits == null) return p;

                if (p.getPageSize() > limits.maxSize())
                    return PageRequest.of(p.getPageNumber(), limits.maxSize(), p.getSort());
                else if (p.getPageSize() < limits.minSize())
                    return PageRequest.of(p.getPageNumber(), limits.minSize(), p.getSort());

                return p;
            }
        };

        resolver.setMaxPageSize(Integer.MAX_VALUE);
        argumentResolvers.add(resolver);
        super.addArgumentResolvers(argumentResolvers);
    }
}

回答by владимир сенцов

Maybe you could use:

也许你可以使用:

@Override
@GetMapping("/some")
public ResponseEntity<Page<BaseEntityInformationDTO>> getTemplateInfo(
              @PageableDefault(sort = "displayedName") Pageable pageable, 
              @RequestParam(defaultValue = Integer.MAX_VALUE + "") Integer trueSize) {
    pageable = new PageRequest(pageable.getPageNumber, Math.max(pageable.getPageSize, trueSize),..)
    ....
}

回答by Triqui

I use this in my code:

我在我的代码中使用它:

public Page<MyObject> retrieveData(@RequestBody CustomParameters query, Pageable pageable, Sort sort) {
    if (pageable == null) {
        return new PageImpl<>(repository.findAll(query.buildSpecification(), sort));
    }
    return repository.findAll(query.buildSpecification(), pageable);
}

This has a couple of advantages. If you use this in controllers you can always define a Pageable and a Sort arguments, if the request contains a "page" parameter, a Pageable will be created automatically (if there is a "sort" parameter it will be included in the pageable if it's not null or in the Sort argument if it is).

这有几个优点。如果你在控制器中使用它,你总是可以定义一个 Pageable 和一个 Sort 参数,如果请求包含一个“page”参数,一个 Pageable 将被自动创建(如果有一个“sort”参数,它将被包含在 pageable 中,如果它不是 null 或在 Sort 参数中(如果是)。

You can customize the sortResolver and pageableResolver in you configuration and then you have the same behaviour in all your controllers.

您可以在配置中自定义 sortResolver 和 pageableResolver,然后您在所有控制器中都具有相同的行为。

This way when you send the request you can specify if you want just a number of records (sendig a "page" parameter, and "size") or if you want them all (not sending those parameters), but you always get the same return structure.

这样,当您发送请求时,您可以指定是否只需要多条记录(发送“页面”参数和“大小”),或者是否需要全部记录(不发送这些参数),但您总是得到相同的回报结构。

回答by bioye

For Spring 5.x.x, set spring.data.rest.max-page-size=2147483647in application.properties.

对于 Spring 5.xx,spring.data.rest.max-page-size=2147483647application.properties.

回答by Viyaan Jhiingade

spring.data.rest.max-page-size=1000

use this property in application.propertyand assign a higher value.

使用此属性application.property并分配更高的值。

回答by Maneki

Here is a working solution for Spring 5.x.x. You just need to add the default constructor. See the above example :

这是 Spring 5.xx 的工作解决方案您只需要添加默认构造函数。看上面的例子:

@Configuration
public class PaginationConfiguration extends SpringDataWebConfiguration {

    /**
     * @param context           must not be {@literal null}.
     * @param conversionService must not be {@literal null}.
     */
    public PaginationConfiguration(ApplicationContext context,
                                   @Qualifier("mvcConversionService") ObjectFactory<ConversionService> conversionService) {
        super(context, conversionService);
    }

    @Bean
    public PageableHandlerMethodArgumentResolver pageableResolver() {
        PageableHandlerMethodArgumentResolver pageableHandlerMethodArgumentResolver =
                new PageableHandlerMethodArgumentResolver(sortResolver());

        pageableHandlerMethodArgumentResolver.setMaxPageSize(Integer.MAX_VALUE);

        return pageableHandlerMethodArgumentResolver;
    }

}