0
0
SpringbootHow-ToBeginner · 4 min read

How to Use Pageable in Spring Data for Pagination

Use Pageable in Spring Data by adding it as a parameter to your repository methods to request paged data. It allows you to specify page number, size, and sorting, and returns a Page object with the results and pagination info.
📐

Syntax

The Pageable interface is used as a method parameter in Spring Data repository interfaces to request paged data. It typically includes page number, page size, and sorting details. The repository method returns a Page<Entity> object containing the data and pagination metadata.

  • Pageable: Interface to specify pagination and sorting.
  • Page<T>: Result wrapper with content and pagination info.
  • PageRequest.of(page, size, sort): Static method to create a Pageable instance.
java
Page<T> findAll(Pageable pageable);
💻

Example

This example shows a Spring Data JPA repository method using Pageable to fetch paged results of Product entities. The controller demonstrates how to create a PageRequest and get paged data with sorting.

java
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

// Entity class
class Product {
    private Long id;
    private String name;
    // getters and setters
}

// Repository interface
interface ProductRepository extends JpaRepository<Product, Long> {
    Page<Product> findAll(Pageable pageable);
}

// Controller class
@RestController
class ProductController {
    private final ProductRepository repository;

    public ProductController(ProductRepository repository) {
        this.repository = repository;
    }

    @GetMapping("/products")
    public List<Product> getProducts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "5") int size
    ) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("name").ascending());
        Page<Product> productPage = repository.findAll(pageable);
        return productPage.getContent();
    }
}
Output
[ {"id":1, "name":"Apple"}, {"id":2, "name":"Banana"}, {"id":3, "name":"Carrot"}, {"id":4, "name":"Date"}, {"id":5, "name":"Eggplant"} ]
⚠️

Common Pitfalls

Common mistakes when using Pageable include:

  • Not passing Pageable to repository methods, causing no pagination.
  • Using zero-based page index but expecting one-based (page 0 is the first page).
  • Ignoring sorting, which can lead to inconsistent results.
  • Returning List instead of Page, losing pagination info.

Always use Page<T> to get total pages and total elements.

java
/* Wrong: Missing Pageable parameter */
List<Product> findAll();

/* Right: Include Pageable parameter */
Page<Product> findAll(Pageable pageable);
📊

Quick Reference

ConceptDescriptionExample
PageableInterface to request page number, size, and sortingPageable pageable = PageRequest.of(0, 10, Sort.by("name"))
PageRequestImplementation of Pageable with static factory methodsPageRequest.of(page, size, sort)
PageResult wrapper with content and pagination metadataPage page = repo.findAll(pageable)
SortingDefines order of resultsSort.by("name").ascending()
Page numberZero-based index of the pagePageRequest.of(0, 5) // first page

Key Takeaways

Use Pageable as a method parameter to enable pagination in Spring Data repositories.
Create Pageable instances with PageRequest.of(page, size, sort) for flexible paging and sorting.
Repository methods should return Page to access both data and pagination info.
Page numbers start at zero, so page 0 is the first page.
Always include sorting to ensure consistent and predictable results.