DEV Community

Cover image for Pagination in Spring Boot with Spring Data JPA
Matheus Bernardes Spilari
Matheus Bernardes Spilari

Posted on

Pagination in Spring Boot with Spring Data JPA

Pagination is an essential feature in APIs that handle large volumes of data. In Spring Boot applications, we can implement pagination easily using Spring Data JPA. In this post, we will see how to modify an endpoint to support pagination.

The Problem

Currently, we have the following method in the controller:

@GetMapping("/")
public ResponseEntity<List<UserModel>> getAllUsers() {
    return ResponseEntity.ok().body(userService.allUsers());
}
Enter fullscreen mode Exit fullscreen mode

This method returns all users at once, which can be inefficient for large datasets. Let's improve this by implementing pagination.

Modifying the Service for Pagination

The first step is to update our repository to extend PagingAndSortingRepository or JpaRepository, as they offer native pagination support in Spring Data JPA:

@Repository
public interface UserRepository extends JpaRepository<UserModel, Long> {
}
Enter fullscreen mode Exit fullscreen mode

Now, let's modify the service to support pagination:

@Service
public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public Page<UserResponseDto> allUsers(Pageable pageable) {
        return userRepository.findAll(pageable).map(user -> new UserResponseDto(user.getId(), user.getName()));
    }}
Enter fullscreen mode Exit fullscreen mode

Updating the Controller

Now, let's update the controller to accept pagination parameters:

@GetMapping("/")
public ResponseEntity<Page<UserResponseDto>> getAllUsers(
        @RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "10") int size,
        @RequestParam(defaultValue = "id") String sortBy) {

    Pageable pageable = PageRequest.of(page, size, Sort.by(sortBy));
    Page<UserResponseDto> users = userService.allUsers(pageable);
    return ResponseEntity.ok().body(users);
}
Enter fullscreen mode Exit fullscreen mode

How to Use Pagination

Now, we can make requests with pagination parameters. Examples:

  • GET /?page=0&size=5 → Returns the first page with 5 users.
  • GET /?page=1&size=10&sortBy=name → Returns the second page with 10 users sorted by name.

Conclusion

With this implementation, we ensure that our API is more efficient and scalable. Pagination prevents data overload and improves the user experience when consuming the API.


📍 Reference

💻 Project Repository

👋 Talk to me

Top comments (0)