DIGITAL GURU
Java DSA Portfolio

Pagination & Sorting (Pageable & Sort)

Implement high-performance zero-indexed database pagination and sorting using Pageable and Page<T>.

Anuj Kumar Singh Written by Anuj Kumar Singh (Lead Engineer, 13+ yrs exp) 5 min read Verified Spring Boot 3+ Guide

Real-World Analogy

Pagination is like reading a 500-page book—instead of dumping 500 pages on your desk at once, you read 10 pages per page flip (Page size = 10, Page index = 0).

Handling High Volume Queries

Fetching thousands of database rows at once exhausts memory. `Pageable` and `Sort` apply SQL `LIMIT` and `OFFSET` clauses at the database level.

Page vs Slice:

  • Page<T>: Executes an additional `COUNT(*)` query to return total pages and record count (ideal for UI paginators).
  • Slice<T>: Fetches next block without running count query (ideal for mobile infinite scrolling).

Production Code Example:

EmployeeController.java
package com.anujsingh.digitalguru.controller;

import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import com.anujsingh.digitalguru.repository.EmployeeRepository;
import com.anujsingh.digitalguru.model.Employee;

@RestController
public class EmployeeController {
    private final EmployeeRepository repository;
    public EmployeeController(EmployeeRepository r) { this.repository = r; }

    @GetMapping("/employees")
    public Page<Employee> getEmployees(@RequestParam(defaultValue="0") int page, @RequestParam(defaultValue="10") int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("lastName").ascending());
        return repository.findAll(pageable);
    }
}

Key Architectural Concepts & Best Practices:

When working with Pagination & Sorting (Pageable & Sort) in enterprise Spring Boot applications, keep these key architectural guidelines in mind:

  • Separation of Concerns: Maintain a strict boundary between HTTP endpoints, service logic, and database persistence layers.
  • Framework Conventions: Rely on Spring Boot auto-configuration defaults whenever possible, overriding settings only via application.yml or @Configuration classes when customized behavior is required.
  • Production Monitoring & Reliability: Ensure proper exception handling, thread-safety, and resource cleanup to prevent memory leaks and unexpected runtime downtime.
  • Developer Ergonomics: Write clean, self-documenting code with modern Java features (Records, Lambdas, Streams) to simplify code reviews and maintenance.

Summary Takeaway:

Mastering Pagination & Sorting (Pageable & Sort) ensures that your Java & Spring Boot backend microservices remain maintainable, secure, and compliant with modern enterprise software engineering standards.

Zero-Index Warning

Spring Data pagination is **0-indexed**! Page 0 is the first page of results.