I am using spring boot with hibernate and I want to use pagination in my project. I have searched on google and saw many examples but I am unable to implement it in my proje
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
2 - Method declaration should be like below example
Page userList(Pageable pageable);
3 - Method implementation in Service class should be like below example
@Override
public Page 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 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