Pagination, Sorting, and Projections
Return paged results with Pageable, sort dynamically, and use interface projections to limit fetched columns.
Why Pagination?
Returning thousands of rows in one query wastes memory and bandwidth. Pagination loads one page at a time. Spring Data integrates pagination with the Pageable abstraction.
Pageable and PageRequest
Create a Pageable using PageRequest.of(page, size). Pass it to any repository method that returns Page<T>.
Pageable pageable = PageRequest.of(0, 20); // page 0, 20 per page
Page<User> page = userRepo.findAll(pageable);
System.out.println("Total: " + page.getTotalElements());
System.out.println("Pages: " + page.getTotalPages());
System.out.println("Content: " + page.getContent().size());All lessons in this course
- Entity Mapping with JPA Annotations
- Spring Data Repositories and Query Methods
- One-to-Many and Many-to-Many Relationships
- Pagination, Sorting, and Projections