Pagination and Sorting in Spring Boot
Introduction :
When working with large amounts of data, fetching all records at once can impact application performance and increase response time.
To solve this problem, Spring Boot provides Pagination and Sorting features through Spring Data JPA.
Pagination allows us to fetch data in smaller chunks (pages), while Sorting helps organize data in ascending or descending order.
In this tutorial, we will learn:
✅ Pagination using Pageable
✅ PageRequest
✅ Sorting using Sort
✅ REST API examples
Why Do We Need Pagination?
Imagine an Employee table containing 10,000 records.
If an API fetches all records at once:
employeeRepository.findAll();
it can:
Increase response time
Consume more memory
Impact application performance
Instead, we can fetch records page by page.
Example:
Page 1 → Records 1-10
Page 2 → Records 11-20
Page 3 → Records 21-30
This approach is more efficient and scalable.
Employee Repository :
Spring Data JPA already provides pagination support through JpaRepository.
@Repository
public interface EmployeeRepository
extends JpaRepository<Employee, Long> {
}
No additional code is required.
Service Layer :
Create a method to fetch paginated employee data.
public Page<Employee> getEmployees(int page, int size) {
Pageable pageable = PageRequest.of(page, size);
return employeeRepository.findAll(pageable);
}
Explanation
page → Current page number
size → Number of records per page
Pageable → Pagination information
PageRequest → Creates Pageable object
Controller Layer :
Create API for pagination.
@GetMapping("/pagination")
public Page<Employee> getEmployees(
@RequestParam int page,
@RequestParam int size) {
return employeeService.getEmployees(page, size);
}
Test API :
Request:
GET /employees/pagination?page=0&size=5
Response:
{
"content": [
{
"id": 1,
"name": "Sulochana",
"email": "sulochana@gmail.com"
}
],
"totalElements": 50,
"totalPages": 10,
"size": 5,
"number": 0
}
Spring Boot automatically returns pagination details.
Sorting Data :
Sorting helps display records in a specific order.
Examples:
Name A to Z
Name Z to A
Latest Records First
Service Layer for Sorting :
public List<Employee> getEmployeesSortedByName() {
return employeeRepository.findAll(
Sort.by("name"));
}
Ascending order is the default behavior.
Descending Order :
public List<Employee> getEmployeesSortedByNameDesc() {
return employeeRepository.findAll(
Sort.by("name").descending());
}
Controller API :
@GetMapping("/sort")
public List<Employee> getEmployeesSorted() {
return employeeService.getEmployeesSortedByName();
}
Request:
GET /employees/sort
Pagination with Sorting :
Spring Boot allows combining pagination and sorting.
public Page<Employee> getEmployeesWithPaginationAndSorting(
int page,
int size) {
Pageable pageable = PageRequest.of(
page,
size,
Sort.by("name").ascending());
return employeeRepository.findAll(pageable);
}
Controller API :
@GetMapping("/pagination-sort")
public Page<Employee> getEmployeesPaginationAndSorting(
@RequestParam int page,
@RequestParam int size) {
return employeeService
.getEmployeesWithPaginationAndSorting(
page,
size);
}
Request:
GET /employees/pagination-sort?page=0&size=5
This API returns paginated and sorted employee records.
Benefits of Pagination and Sorting :
Improved performance
Faster response times
Better user experience
Reduced memory consumption
Easy navigation through large datasets
Conclusion :
In this tutorial, we learned how to implement Pagination and Sorting in Spring Boot using Spring Data JPA.
We covered:
✅ Pageable
✅ PageRequest
✅ Sort
✅ Pagination API
✅ Sorting API
✅ Pagination with Sorting
These features are widely used in real-world applications to efficiently manage and display large amounts of data.
In the next tutorial, we will learn how to implement Validation in Spring Boot using @Valid and Bean Validation.
Comments
Post a Comment