How to implement pagination in spring boot with hibernate
I would consider using org.springframework.data.domain.Pageable
directly into your controller. This object can then be passed to your JPA layer where it will handle the number of returned results and the size.
The great thing about using Pageable
is that it returns a Page
object which can be used on the front-end to form previous/next page logic.
By default this class uses url parameters 'page' and 'size'; hence page=0&size=10 will return the first 10 items.
Hence in your case the code could look something like:
@ResponseBody
@RequestMapping("/top/pages/")
public List<Post> getAllPosts(@PageableDefault(value=10, page=0) Pageable pageable) throws ServletException {
Page page = postDao.findAll(pageable);
return page.getContent();
}
Notice the annotation @PageableDefault
is just to set up the defaults & it's not required.
In the front-end the next page call can be <a href="/top/pages?page=1">Next</a>
; this will return a list of Posts from 11 to 20.
Implement pagination in Spring Boot is quite easy only you need to follow basic steps -
1 - Extends PagingAndSortingRepository in repository interface
public interface UserRepository extends PagingAndSortingRepository <User, Long>
2 - Method declaration should be like below example
Page<User> userList(Pageable pageable);
3 - Method implementation in Service class should be like below example
@Override
public Page<User> userList(Pageable pageable) {
return userRepository.findAll(pageable);
}
4 - Controller class code should be like below
@GetMapping("/list")
public String userList(Model model, Pageable pageable) {
Page<User> pages = userService.userList(pageable);
model.addAttribute("number", pages.getNumber());
model.addAttribute("totalPages", pages.getTotalPages());
model.addAttribute("totalElements",
pages.getTotalElements());
model.addAttribute("size", pages.getSize());
model.addAttribute("users", pages.getContent());
return "/user/list";
}
From front-end call should be like below
http://localhost:8080/application/user/list?page=0&size=5
http://localhost:8080/application/user/list?page=1&size=5
http://localhost:8080/application/user/list?page=2&size=5
For more details watch below video
Spring Boot : Pagination Basic
Spring Boot : Pagination Advanced
Thanks for reading