Sorting and Paging
Sorting and paging order a list and split it into pages. Sort sets the order and Pageable sets the page.
Order by title
Sort.by names the field to order by.
Sort sort = Sort.by("title");Ask for one page
PageRequest.of takes a page number and a page size. Pages start at 0.
Pageable firstPage = PageRequest.of(0, 2);Example
package com.example.demo;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaskController {
private final TaskRepository repository;
public TaskController(TaskRepository repository) {
this.repository = repository;
}
@GetMapping("/tasks")
public List<TaskView> pagedTasks(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "2") int size) {
Page<Task> result = repository.findAll(
PageRequest.of(page, size, Sort.by("title")));
return result.stream()
.map(task -> new TaskView(task.getTitle(), task.isDone()))
.toList();
}
public record TaskView(String title, boolean done) {
}
}Key points
- Sort.by names the field to order by.
- PageRequest.of takes a page number and a page size.
- Pages start at 0, so page 0 is the first page.
- A Page holds the tasks plus the page facts.
- The repository method takes a Pageable.
- Sorting by title puts Buy milk first.
In this example, TaskController holds the repository in a field. The constructor receives the repository when Spring builds the controller. The pagedTasks method takes a page number and a size from the address. It builds a PageRequest with Sort.by("title"), so the list is ordered by title. The repository returns one page of tasks. The first exchange shows page 0, the first two titles in order. The second exchange shows page 1, the last title.
Note
Ask for a page beyond the last one and the answer is an empty list.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does PageRequest.of(1, 2) ask for?