Retrieving large amounts of data from a database can significantly impact application performance. Returning thousands of rows in a single API response consumes memory, increases response times and creates a poor user experience.
Spring Data JPA provides built-in support for Pagination and Sorting, allowing applications to fetch only the required records efficiently.
What is Pagination?
Pagination is the process of dividing data into smaller chunks called pages. Instead of loading all records at once, only a subset of records is returned.
Without Pagination
SELECT *
FROM employees;
This query returns every employee record. For large tables, this approach is inefficient.
With Pagination
Page 1 -> Records 1 to 10
Page 2 -> Records 11 to 20
Page 3 -> Records 21 to 30
Only the requested page is loaded.
What is Sorting?
Sorting allows records to be returned in a specific order.
Examples
- Sort by Salary
- Sort by Employee Name
- Sort by Joining Date
- Sort by Department
Sorting improves usability and data presentation.
Project Structure
controller
EmployeeController
service
EmployeeService
repository
EmployeeRepository
entity
Employee
Employee Entity
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(
strategy =
GenerationType.IDENTITY
)
private Long id;
private String name;
private String department;
private Double salary;
}
Repository Layer
Pagination support is automatically available through JpaRepository.
@Repository
public interface EmployeeRepository
extends JpaRepository<
Employee,
Long> {
}
Fetching Data Using Pagination
Spring Data JPA uses the Pageable interface.
Pageable pageable =
PageRequest.of(
0,
5
);
Page<Employee>
employees =
repository.findAll(pageable);
Parameters
- 0 = Page Number
- 5 = Records Per Page
This loads the first five employees.
Service Layer Example
@Service
public class EmployeeService {
private final
EmployeeRepository repository;
public EmployeeService(
EmployeeRepository repository) {
this.repository = repository;
}
public Page<Employee>
getEmployees(
int page,
int size) {
Pageable pageable =
PageRequest.of(
page,
size
);
return repository
.findAll(pageable);
}
}
Controller Example
@GetMapping
public Page<Employee>
getEmployees(
@RequestParam int page,
@RequestParam int size) {
return service
.getEmployees(
page,
size
);
}
API Call Example
GET
/employees?page=0&size=5
This returns the first page with 5 records.
Pagination Response
{
"content": [
{
"id": 1,
"name": "John"
}
],
"totalPages": 5,
"totalElements": 25,
"size": 5,
"number": 0
}
Sorting Example
Sorting is implemented using the Sort class.
Sort sort =
Sort.by("salary");
repository.findAll(sort);
Employees are sorted by salary in ascending order.
Descending Sort Example
Sort sort =
Sort.by("salary")
.descending();
repository.findAll(sort);
Highest salaries appear first.
Multiple Column Sorting
Sort sort =
Sort.by("department")
.ascending()
.and(
Sort.by("salary")
.descending()
);
Results are grouped by department and sorted by salary within each department.
Pagination and Sorting Together
Pageable pageable =
PageRequest.of(
0,
5,
Sort.by("salary")
.descending()
);
repository.findAll(pageable);
This is one of the most common approaches in production applications.
REST API Example
GET
/employees
?page=0
&size=10
&sort=salary,desc
This fetches ten employees sorted by salary in descending order.
Why Pagination is Important
- Reduces memory usage
- Improves API performance
- Supports large datasets
- Faster response times
- Better user experience
Real Interview Questions
What is Pageable?
Pageable is an interface used to define pagination information such as page number and page size.
What is Page?
Page is a paginated result that contains records and pagination metadata.
Can Sorting and Pagination be used together?
Yes. This is a very common production use case.
Which repository supports pagination?
PagingAndSortingRepository and JpaRepository.
What happens if pagination is not implemented?
Large datasets may slow down applications and consume unnecessary memory.
Best Practices
- Always paginate large datasets.
- Use sensible page sizes.
- Avoid returning thousands of records.
- Combine sorting with pagination.
- Validate page and size parameters.
Frequently Asked Questions (FAQ)
What is the difference between List and Page?
List contains only data, while Page contains data along with pagination information.
Can pagination improve performance?
Yes. It reduces the amount of data loaded into memory.
Does JpaRepository support sorting automatically?
Yes. Sorting support is built into JpaRepository.
Conclusion
Pagination and Sorting are essential techniques for building efficient Spring Boot applications. Spring Data JPA provides powerful built-in support using Pageable, PageRequest and Sort, making it easy to handle large datasets while maintaining excellent application performance.
Keywords
Pagination Spring Data JPA, Sorting Spring Data JPA, Spring Boot Pagination, JpaRepository Pagination, Pageable Example, PageRequest Example, Sorting Example Spring Data JPA, Spring Boot REST API Pagination, Pagination and Sorting Interview Questions, Spring Data JPA Tutorial, Spring Boot Database Performance, Java Backend Development, JPA Paging Example, Spring Boot CRUD, Spring Framework Tutorial
Reviewed by 13thGhost
on
3:17 AM
Rating:

No comments: