00:00

Spring Boot Pagination and Sorting

In real-world applications, databases often contain large amounts of data. Fetching all records at once can cause performance issues and slow response times. Pagination and sorting in Spring Boot help retrieve data in smaller chunks and in a specific order, making applications faster and more user-friendly.

What Is Pagination?

Pagination means dividing a large dataset into smaller pages. Instead of returning thousands of records, the application returns only a limited number of records per request.

Example:

  • Page 0 → First 10 records
  • Page 1 → Next 10 records
  • Page 2 → Next 10 records

What Is Sorting?

Sorting means arranging data in a specific order, such as ascending or descending.

Common sorting examples:

  • Sort users by name (A → Z)
  • Sort products by price (high → low)
  • Sort orders by creation date

Why Use Pagination and Sorting?

  • Improves application performance
  • Reduces memory consumption
  • Provides better user experience
  • Makes APIs scalable

Spring Data JPA Support

Spring Boot provides built-in support for pagination and sorting through Spring Data JPA. The key interfaces are:

  • Pageable
  • Page
  • Sort

Repository Example

To enable pagination and sorting, your repository should extend JpaRepository.

      
  public interface UserRepository 
          extends JpaRepository<User, Long> {
  }
      
    

Pagination Using Pageable

The Pageable interface represents pagination information such as page number and page size.

      
  @GetMapping("/users")
  public Page<User> getUsers(
          @RequestParam int page,
          @RequestParam int size) {
  
      Pageable pageable = PageRequest.of(page, size);
      return userRepository.findAll(pageable);
  }
      
    

Understanding Page Object

The Page object provides useful metadata along with data.

  • Total elements
  • Total pages
  • Current page number
  • Page size

Sorting Using Sort

Sorting can be applied using the Sort class.

      
  @GetMapping("/users/sort")
  public List<User> getSortedUsers() {
      return userRepository.findAll(
          Sort.by(Sort.Direction.ASC, "name")
      );
  }
      
    

Pagination with Sorting

Pagination and sorting are often used together.

      
  @GetMapping("/users/page-sort")
  public Page<User> getUsersWithPaginationAndSorting(
          @RequestParam int page,
          @RequestParam int size,
          @RequestParam String sortBy) {
  
      Pageable pageable = PageRequest.of(
          page, size, Sort.by(sortBy).ascending()
      );
  
      return userRepository.findAll(pageable);
  }
      
    

Using Default Pagination Parameters

Spring Boot allows default pagination using @PageableDefault.

      
  @GetMapping("/users/default")
  public Page<User> getUsers(
      @PageableDefault(size = 10, sort = "id") Pageable pageable) {
      return userRepository.findAll(pageable);
  }
      
    

Best Practices

  • Use pagination for all list APIs
  • Limit maximum page size to avoid misuse
  • Validate sort fields to prevent errors
  • Return metadata along with paged data

Common Mistakes to Avoid

  • Using large page sizes
  • Not handling invalid page numbers
  • Sorting on non-indexed columns
  • Returning full entities unnecessarily

Conclusion

Pagination and sorting are essential features for building scalable Spring Boot applications. With Spring Data JPA, implementing them is simple and efficient. By using Pageable, Page, and Sort correctly, developers can build high-performance and user-friendly APIs.