What is pagination and how to implement pagination in spring data?

Pagination is the technique of splitting a large result set into smaller, fixed-size pages that can be retrieved one at a time instead of loading everything at once. Spring Data JPA implements this natively through the Pageable interface, which repository methods can accept as a parameter.

Key Points: • Passing a Pageable to a repository method (e.g. findAll(Pageable pageable)) automatically applies LIMIT/OFFSET-style paging at the database level. • PageRequest.of(page, size, sort) builds a Pageable specifying the page number, page size, and optional sorting. • The return type Page<T> includes metadata like total elements, total pages, and whether there is a next/previous page, while Slice<T> is a lighter alternative without a total count query. • Combining pagination with sorting is done through the Sort parameter embedded in the PageRequest. • Server-side pagination avoids loading and transferring huge result sets, which is critical for both performance and memory usage.

Example: A product listing endpoint returning thousands of products would accept a page number and size from the client, use PageRequest.of(page, size) to build a Pageable, and return only that slice of results along with total page count for building a UI pager.

Code Example:

public interface ProductRepository extends JpaRepository<Product, Long> {
}

// In a service or controller
Pageable pageable = PageRequest.of(0, 20, Sort.by("name").ascending());
Page<Product> productPage = productRepository.findAll(pageable);

List<Product> products = productPage.getContent();
int totalPages = productPage.getTotalPages();

Interview Tip: A concise interview answer is:

"Pagination breaks a large result set into pages, and in Spring Data JPA I implement it by passing a Pageable, built with PageRequest.of(page, size, sort), into a repository method. The method returns a Page<T> that carries the content plus metadata like total pages and elements, so the database only fetches the rows for that one page instead of the whole table."