Easy Pagination With Spring Data and MVC

Last Update: 31.08.2017. By Jens in Spring Boot | Spring Data | Spring MVC

In this tutorial, I show you an easy way for handling pagination when you use Spring Data and Spring MVC in your application you might not be aware of.

Pagination in Spring Data

Spring Data offers two classes/interfaces for pagination:

  • Pageable is an interface defining a request for a page with number of the page, how many items per page and an optional sorting
  • Page is the return object for such a paging method and contains the actual result plus some meta data like total matches, pages, items per page, etc

You can use Pageable as a method parameter on any of your repository methods, and Spring Data executes the query accordingly. Your method can then return a Page and give the caller of your method a way to navigate through your data set.

Pagination in Spring MVC

Usually, you will just return the Page in Spring MVC @Controller and your client can build the pagination accordingly. When the client selects a new page or page size, it sends that info as parameters to your @Controller. In the @Controller, we could create a Pageable manually (PageRequest is the default implementation) and pass it down to the repository. Or, we can remove that manual mapping and let Spring Data take over. We will do the latter.

First, we must enable this feature of Spring Data by setting the @EnableSpringDataWebSupport annotation on our Spring Boot class or any other @Configuration.

@SpringBootApplication
@EnableSpringDataWebSupport
public class SpringDataMongodbTutorialApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringDataMongodbTutorialApplication.class, args);
    }
}

Second, in our @Controller method, we can now pass a Pageable as a method parameter along, and Spring Data’s web support will do the mapping for us.

@RestController
public class UserController {

  @Autowired UserRepository repository;

  @RequestMapping("/users")
  public Page<User> showUsers(Pageable pageable) {
    return repository.findAll(pageable);
  }
}

By, default, it maps as followed:

  • page = page you want to retrieve; default: 0.
  • size = items per page; default: 20.
  • sort = sorting in the form of property,property(,ASC|DESC), e.g: ?sort=lastname,desc Multiple parameters supported

In case you want different default values for the page request, you can add the @PageableDefaults to the Pageable parameter in the controller method and change the values.

Conclusion

A little annotation makes the pagination a breeze in MVC. Furthermore, it works for Sort too.