Pagination and Sorting with Spring Data JPA
Last Updated :
24 Oct, 2025
When dealing with large datasets, retrieving all records at once is inefficient and can affect application performance. To handle such cases effectively, pagination (retrieving data in smaller chunks) and sorting (ordering records by specific fields) are essential.
Pagination divides large datasets into smaller, manageable pages that can be fetched one at a time. For example, instead of loading 1,000 records, you can retrieve 10 records per page.
2. Sorting
Sorting arranges records based on one or more fields, such as ordering products by name or price. It helps improve data presentation and retrieval efficiency.
Implementation: Pagination and Sorting in Spring Data JPA
Step 1: Create a Spring Boot Project
Create a new Spring Boot project with the following details:
- Name: spring-sorting-pagination-demo
- Language: Java
- Type: Maven
- Packaging: Jar
Step 2: Add the dependencies
Add the following dependencies into the project.
DependenciesStep 3: Project Structure
Once created the project, the file structure looks like:
StructureSet up your database configuration in application.properties:
spring.application.name=spring-sorting-pagination-demo
spring.datasource.url=jdbc:mysql://localhost:3306/product_db
spring.datasource.username=root
spring.datasource.password=mypassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
Step 5: Create the Entity Class
Product.java:
Java
package com.gfg.springsortingpaginationdemo;
import jakarta.persistence.*;
import lombok.*;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Double price;
}
Step 6: Create the Repository Interface
ProductRepository.java
Java
package com.gfg.springsortingpaginationdemo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
Note: JpaRepository extends PagingAndSortingRepository, so you get pagination and sorting functionality without needing both.
Step 7: Create the Service Class
ProductService.java:
Java
package com.gfg.springsortingpaginationdemo;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public Page<Product> findAll(Pageable pageable) {
return productRepository.findAll(pageable);
}
}
Step 8: Create the Controller Class
ProductController.java:
Java
package com.gfg.springsortingpaginationdemo;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/products")
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping
public Page<Product> getAllProducts(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "5") int size,
@RequestParam(defaultValue = "id") String sortBy,
@RequestParam(defaultValue = "true") boolean ascending) {
Sort sort = ascending ? Sort.by(sortBy).ascending() : Sort.by(sortBy).descending();
Pageable pageable = PageRequest.of(page, size, sort);
return productService.findAll(pageable);
}
}
Step 9: Main Class
Java
package com.gfg.springsortingpaginationdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
@SpringBootApplication
@EnableSpringDataWebSupport(pageSerializationMode = EnableSpringDataWebSupport.PageSerializationMode.VIA_DTO)
public class SpringSortingPaginationDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSortingPaginationDemoApplication.class, args);
}
}
Step 10: Run the Application
Run the application. By default, it will start on port 8080.
OutputStep 11: Testing the Endpoint
To test the endpoint, use:
http://localhost:8080/products?page=0&size=5&sortBy=price&ascending=false
This fetches the first page of products, showing 5 records sorted by price in descending order.
Output
Explore
Java Enterprise Edition
Multithreading
Concurrency
JDBC (Java Database Connectivity)
Java Frameworks
JUnit