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);
}