Pagination & Sorting
Returning all rows from GET /api/tasks works with ten tasks and collapses with ten million. Pagination returns one slice at a time, and sorting decides the order. Spring Data makes both nearly automatic: repository methods accept a Pageable, and Spring MVC builds that Pageable from ?page=, ?size= and ?sort= query parameters.
Pageable in the repository
public interface TaskRepository extends JpaRepository<Task, Long> {
Page<Task> findByDone(boolean done, Pageable pageable);
Slice<Task> findByTitleContainingIgnoreCase(String q, Pageable pageable);
}findAll(Pageable) is inherited from JpaRepository already.
| Return type | Contains | Extra query |
|---|---|---|
Page<T> |
content + total elements + total pages | yes, a count(*) |
Slice<T> |
content + "is there a next slice?" | no (fetches size + 1 rows) |
List<T> |
content only | no |
Pageable in the controller
@GetMapping
PagedModel<TaskResponse> list(@RequestParam(defaultValue = "false") boolean done,
@PageableDefault(size = 20, sort = "dueDate") Pageable pageable) {
Page<TaskResponse> page = repository.findByDone(done, pageable).map(TaskResponse::from);
return new PagedModel<>(page);
}Since Spring Data 3.3, returning a Page directly logs a warning, because its JSON structure is an implementation detail that may change. PagedModel (or enabling @EnableSpringDataWebSupport(pageSerializationMode = VIA_DTO)) produces a stable format:
curl -s "localhost:8080/api/tasks?page=1&size=2&sort=title,desc" | jq{
"content": [
{
"id": 4,
"title": "Plan sprint",
"description": null,
"priority": "HIGH",
"done": false,
"projectName": "Website"
},
{
"id": 1,
"title": "Learn Spring Boot",
"description": null,
"priority": "MEDIUM",
"done": false,
"projectName": "Website"
}
],
"page": {
"size": 2,
"number": 1,
"totalElements": 5,
"totalPages": 3
}
}
The SQL Hibernate generates for that request (H2 dialect):
Hibernate: select t1_0.id,... from tasks t1_0 where t1_0.done=? order by t1_0.title desc offset ? rows fetch first ? rows only
Hibernate: select count(t1_0.id) from tasks t1_0 where t1_0.done=?The query parameters
| Parameter | Example | Meaning |
|---|---|---|
page |
page=0 |
zero-based page index |
size |
size=20 |
items per page (capped at 2000 by default) |
sort |
sort=dueDate |
ascending by dueDate |
sort=title,desc |
descending | |
sort=priority,desc&sort=title |
several sort keys |
Configure defaults globally:
spring.data.web.pageable.default-page-size=20
spring.data.web.pageable.max-page-size=100
spring.data.web.pageable.one-indexed-parameters=falseThe arithmetic behind a page
Offset pagination is simple maths: offset = page * size, totalPages = ceil(total / size). This program implements a small Page over an in-memory list, with sorting by a key:
import java.util.*;
record Task(long id, String title, int priority) {}
record Page<T>(List<T> content, int number, int size, long totalElements) {
int totalPages() { return (int) Math.ceil((double) totalElements / size); }
boolean hasNext() { return number + 1 < totalPages(); }
}
class Main {
static Page<Task> findAll(List<Task> all, int page, int size, Comparator<Task> sort) {
List<Task> sorted = all.stream().sorted(sort).toList();
int from = Math.min(page * size, sorted.size());
int to = Math.min(from + size, sorted.size());
return new Page<>(sorted.subList(from, to), page, size, sorted.size());
}
public static void main(String[] args) {
List<Task> tasks = List.of(
new Task(1, "Learn Spring Boot", 2), new Task(2, "Write a controller", 1),
new Task(3, "Read the docs", 1), new Task(4, "Plan sprint", 3), new Task(5, "Deploy", 3));
Comparator<Task> byTitleDesc = Comparator.comparing(Task::title).reversed();
for (int p = 0; p < 4; p++) {
Page<Task> page = findAll(tasks, p, 2, byTitleDesc);
System.out.printf("page %d/%d hasNext=%-5b %s%n", page.number(), page.totalPages(), page.hasNext(),
page.content().stream().map(Task::title).toList());
}
Comparator<Task> byPriorityDescThenTitle =
Comparator.comparingInt(Task::priority).reversed().thenComparing(Task::title);
System.out.println(findAll(tasks, 0, 3, byPriorityDescThenTitle).content());
}
}page 0/3 hasNext=true [Write a controller, Read the docs]
page 1/3 hasNext=true [Plan sprint, Learn Spring Boot]
page 2/3 hasNext=false [Deploy]
page 3/3 hasNext=false []
[Task[id=5, title=Deploy, priority=3], Task[id=4, title=Plan sprint, priority=3], Task[id=1, title=Learn Spring Boot, priority=2]]
Requesting a page beyond the end is not an error — it simply returns an empty content.
Building Pageable and Sort in code
Pageable firstTen = PageRequest.of(0, 10, Sort.by("dueDate").ascending().and(Sort.by("title")));
Page<Task> page = repository.findAll(firstTen);
List<Task> urgent = repository.findByDone(false, Sort.by(Sort.Direction.DESC, "priority"));Protect against arbitrary sort fields
?sort= accepts any entity property, including ones you may not want users to sort by (or that have no index). Restrict it:
private static final Set<String> SORTABLE = Set.of("title", "dueDate", "priority");
if (pageable.getSort().stream().anyMatch(o -> !SORTABLE.contains(o.getProperty()))) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "unsupported sort field");
}Tip: Offset pagination becomes slow for very deep pages (
offset 1000000), because the database must skip all those rows. For infinite scrolling over large tables, use keyset pagination: "give me 20 tasks with id greater than the last one I saw". Spring Data supports this withScrollPositionandWindow<T>.
Test yourself
With ?page=2&size=10, which rows does an offset query return?
- Rows 1-10
- Rows 11-20
- Rows 21-30
- Rows 2-12
What is the advantage of returning Slice instead of Page?
- It sorts automatically
- It avoids the extra count query
- It returns all rows
- It caches results
How do you request descending order by title through query parameters?
?order=title-?sort=title,desc?sortDesc=title?sort=-title