Set default page size for JPA Pageable Object

后端 未结 8 1787
忘掉有多难
忘掉有多难 2020-12-01 09:11

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.

My

8条回答
  •  青春惊慌失措
    2020-12-01 10:05

    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.

    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 Pageable instance base on a request Pageable and configured page size

    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):

    @Value("${myapplication.model.items-per-page:20}")
    private int itemsPerPage;
    

    And then I override (i.e. create a new Pageable instance) default page size in request handling method:

    @RequestMapping(method = RequestMethod.GET)
    public Page 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.

提交回复
热议问题