Hackforge Academy

Category: spring_boot

Pagination in spring boot

Published on 26 Jun 2026

Explanation

Pagination is used to retrieve large datasets in smaller chunks. Instead of returning all records at once, the API returns a specific page of data. Spring Data JPA provides built-in support for pagination using Pageable.

Code:

import org.springframework.data.jpa.
repository.JpaRepository;

public interface StudentRepository 
extends JpaRepository<Student, Long> {
}

Explanation

The Pageable interface allows clients to specify the page number and page size. Spring automatically creates a Pageable object from request parameters.

Code:

@GetMapping("/students")
public Page<Student> getStudents(
Pageable pageable) {
    return studentRepository.findAll(
pageable);
}

Explanation

Pagination can be controlled explicitly using page and size query parameters. The PageRequest class creates a Pageable instance with the desired settings.

Code:

@GetMapping("/students")
public Page<Student> getStudents(
        @RequestParam int page,
        @RequestParam int size) {

    Pageable pageable =
 PageRequest.of(page, size);
    return studentRepository.findAll(
pageable);
}

Explanation

Sorting allows records to be returned in ascending or descending order based on a field. The Sort class is used to define sorting criteria.

Code:

@GetMapping("/students/sorted")
public List<Student> getSortedStudents() {
    return studentRepository.findAll(
            Sort.by("name").ascending()
    );
}

Explanation

Pagination and sorting can be combined to efficiently retrieve ordered data. This is commonly used in production APIs to improve performance and user experience.

Code:

@GetMapping("/students/paged")
public Page<Student> getPagedStudents(
        @RequestParam int page,
        @RequestParam int size) {

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

    return studentRepository.
findAll(pageable);
}

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community