Pagination helps show data in small parts instead of all at once. Sorting arranges data in order. Pageable makes both easy in Spring Boot.
Pagination and sorting with Pageable in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.by("fieldName").ascending());
Page<Entity> page = repository.findAll(pageable);PageRequest.of() creates a Pageable object with page number, size, and sort.
Page numbers start at 0, so page 0 is the first page.
Pageable pageable = PageRequest.of(0, 5);
Pageable pageable = PageRequest.of(1, 10, Sort.by("name").ascending());
Pageable pageable = PageRequest.of(0, 20, Sort.by("price").descending());
This Spring Boot app shows how to get products with pagination and sorting.
The controller method accepts page number, size, sort field, and order from URL parameters.
It creates a Pageable object and fetches a page of products from the database.
The result is a list of products for that page and order.
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; 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 jakarta.persistence.Entity; import jakarta.persistence.Id; import java.util.List; @SpringBootApplication public class PaginationSortingApp { public static void main(String[] args) { SpringApplication.run(PaginationSortingApp.class, args); } } @Entity class Product { @Id private Long id; private String name; private double price; public Product() {} public Product(Long id, String name, double price) { this.id = id; this.name = name; this.price = price; } public Long getId() { return id; } public String getName() { return name; } public double getPrice() { return price; } @Override public String toString() { return String.format("Product{id=%d, name='%s', price=%.2f}", id, name, price); } } interface ProductRepository extends JpaRepository<Product, Long> {} @RestController class ProductController { private final ProductRepository repository; ProductController(ProductRepository repository) { this.repository = repository; } @GetMapping("/products") public List<Product> getProducts( @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "5") int size, @RequestParam(defaultValue = "name") String sortBy, @RequestParam(defaultValue = "asc") String order) { Sort sort = order.equalsIgnoreCase("desc") ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending(); Pageable pageable = PageRequest.of(page, size, sort); Page<Product> productPage = repository.findAll(pageable); return productPage.getContent(); } }
Page numbers start at 0, so the first page is page 0.
Sorting fields must match entity property names exactly.
Use Page.getTotalPages() to know how many pages exist.
Pageable helps get data in small pages with sorting.
Use PageRequest.of(page, size, sort) to create Pageable.
Combine pagination and sorting in one easy step with Spring Data.
Practice
Pageable in Spring Boot?Solution
Step 1: Understand Pageable's role
Pageableis used to request data in pages, not all at once.Step 2: Recognize sorting feature
It also supports sorting data by fields while fetching pages.Final Answer:
To fetch data in small chunks with optional sorting -> Option AQuick Check:
Pageable = Pagination + Sorting [OK]
- Thinking Pageable connects to database
- Confusing Pageable with authentication
- Assuming Pageable writes SQL queries
Pageable object for page 2, size 5, sorted by "name" ascending?Solution
Step 1: Understand zero-based page index
Page numbers start at 0, so page 2 means index 1.Step 2: Check method and sorting syntax
UsePageRequest.of(page, size, Sort.by("field"))for ascending sort.Final Answer:
PageRequest.of(1, 5, Sort.by("name")) -> Option AQuick Check:
Page index zero-based + Sort.by correct [OK]
- Using page number directly instead of zero-based index
- Using non-existent methods like Sort.asc
- Using PageRequest.create instead of PageRequest.of
repository.findAll(PageRequest.of(0, 3, Sort.by("age")))What will be the result?
Solution
Step 1: Analyze PageRequest parameters
Page 0 means first page, size 3 means 3 records, Sort.by("age") defaults to ascending.Step 2: Understand repository behavior
findAll with Pageable returns that page of sorted data.Final Answer:
First 3 records sorted by age ascending -> Option DQuick Check:
Page 0 + size 3 + ascending sort = first 3 sorted [OK]
- Assuming descending sort without direction
- Thinking all records are returned
- Expecting error due to missing direction
Pageable pageable = PageRequest.of(1, 10, Sort.asc("date"));Solution
Step 1: Check Sort method usage
Spring Data usesSort.by(), notSort.asc().Step 2: Verify other parameters
Page index 1 and size 10 are valid;PageRequest.oftakes 3 parameters here.Final Answer:
Sort.asc() method does not exist -> Option BQuick Check:
Use Sort.by() for sorting [OK]
- Using Sort.asc() or Sort.desc() which don't exist
- Thinking page index must be 0 always
- Believing PageRequest.of needs 4 parameters
Pageable creation is correct?Solution
Step 1: Identify zero-based page index
Third page means index 2 (0,1,2).Step 2: Create Sort with multiple orders
UseSort.by(Order.desc("price"), Order.asc("name"))to combine sorting directions.Step 3: Check syntax correctness
PageRequest.of(2, 4, Sort.by(Sort.Order.desc("price"), Sort.Order.asc("name"))) uses correctPageRequest.ofandSort.bywith orders.Final Answer:
PageRequest.of(2, 4, Sort.by(Sort.Order.desc("price"), Sort.Order.asc("name"))) -> Option CQuick Check:
Page 2 + size 4 + multi-sort orders correct [OK]
- Using page number 3 instead of index 2
- Trying to chain .desc() or .asc() methods that don't exist
- Passing multiple fields without specifying order
