Java  

How to Implement Pagination and Sorting in Spring Boot Using Spring Data JPA?

๐ŸŒฑ Introduction

In real-world enterprise applications, especially those handling large amounts of data, returning the complete dataset in one go is neither practical nor efficient. That's where pagination and sorting become essential components of your API design.

Pagination breaks down the data into manageable chunks (pages), improving performance and reducing memory usage. Sorting enables users to view the data in a meaningful order, ascending, descending, alphabetical, numerical, etc.

Spring Data JPA offers built-in support for both features via Pageable and Sort objects. This tutorial explains how to implement them with step-by-step instructions and Java code examples.

๐Ÿ“ฆ Add Required Dependencies

Make sure your project includes Spring Data JPA and a database connector (H2, MySQL, PostgreSQL, etc.).

If you use Spring Boot Starter, JPA support is already included:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

You also need a database dependency:

<!-- Example for H2 Database -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

๐Ÿงฑ Define Your Entity Class

Let's assume you're working with a simple Product entity:

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private Double price;

    // Constructors, Getters, and Setters
}

๐Ÿ“‚ Create the Repository Interface

Spring provides a PagingAndSortingRepository interface, which supports both pagination and sorting operations out of the box.

public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {

    Page<Product> findByNameContaining(String name, Pageable pageable);
}

You can also use JpaRepository, which extends PagingAndSortingRepository:

public interface ProductRepository extends JpaRepository<Product, Long> {
}

โš™๏ธ Implement the Service Layer

This layer handles the business logic. Here’s how you create a paginated and sortable query using PageRequest and Sort:

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public Page<Product> getProducts(int page, int size, String sortBy) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(sortBy));
        return productRepository.findAll(pageable);
    }
}

๐ŸŒ Build the REST Controller

Expose an endpoint that accepts pagination and sorting parameters from the client:

@RestController
@RequestMapping("/products")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping
    public Page<Product> getPaginatedProducts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "5") int size,
            @RequestParam(defaultValue = "id") String sortBy) {

        return productService.getProducts(page, size, sortBy);
    }
}

๐Ÿงช Example API Request

Here’s a sample GET request with pagination and sorting parameters:

GET /products?page=0&size=10&sortBy=price

This request returns:

  • First page of data (index 0)
  • 10 products per page
  • Sorted by the price field

๐ŸŽฏ Advanced Sorting with Multiple Fields

You can chain multiple sort conditions using Sort:

Sort sort = Sort.by("name").ascending().and(Sort.by("price").descending());
Pageable pageable = PageRequest.of(page, size, sort);

This sorts the result first by name in ascending order, then by price in descending order.

๐Ÿ“ˆ Understanding the Page Object Structure

The Page<T> object returned by Spring contains:

  • getContent(): List of entities for the current page
  • getTotalPages(): Total number of pages
  • getTotalElements(): Total number of elements
  • getNumber(): Current page index
  • getSize(): Size of the page

This makes it easy to render UI components like pagination controls in frontend apps.

๐ŸŒŸ Benefits of Using Pagination and Sorting

  • โœ… Improves backend performance by loading only a subset of data
  • ๐ŸŒ Reduces network load in RESTful services
  • ๐Ÿ“ฒ Optimizes frontend rendering, especially with large tables or lists
  • ๐Ÿ“š Easy to use with minimal configuration in Spring Boot

๐Ÿงต Final Takeaway

Implementing pagination and sorting in Spring Boot with Spring Data JPA is straightforward and efficient. With just a few lines of code, you can handle large datasets while keeping your API performant, maintainable, and user-friendly.

Use Pageable and Sort objects, and allow your REST clients to dynamically request data in the format and structure they need. This not only improves performance but also enhances user experience across web and mobile platforms.