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.
Spring Data offers two classes/interfaces for pagination:
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.
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:
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.
A little annotation makes the pagination a breeze in MVC. Furthermore, it works for Sort too.