Sub topic 13
Paginating and sorting collections
This chapter adds paging and sorting to GET /api/books. It assumes you have the BookRepository, BookService, and BookController from the earlier chapters, and that you know basic JPA and SQL. You should also know what LIMIT, OFFSET, and ORDER BY do.
Why unbounded lists cause trouble
A findAll() that returns every row works with ten books. With a million rows it loads them all into memory, serializes them, and sends a huge response. Pagination limits each response to one slice of the data. Sorting makes the order of the slices predictable.
The code you wrote in the service and controller chapters already supports both. The Pageable parameter and the Page return type do the work. This chapter explains what they do and where they can fail.
How a request becomes a page
Spring Data registers a PageableHandlerMethodArgumentResolver and a SortHandlerMethodArgumentResolver with Spring MVC. When a controller method declares a Pageable parameter, the resolver reads query parameters and builds the object.
| Parameter | Meaning | Default |
|---|---|---|
| `page` | Zero-based page index | `0` |
| `size` | Number of elements per page | `20` |
| `sort` | `property,direction`. Repeat the parameter for several sort keys. | unsorted |
For example, this request asks for the third page of five books, ordered by author and then by title descending:
GET /api/books?page=2&size=5&sort=author,asc&sort=title,descThe resolver turns that into PageRequest.of(2, 5, Sort.by(Order.asc("author"), Order.desc("title"))). The controller passes it to the service, and the service passes it to repository.findAll(pageable). Spring Data then issues two SQL statements.
The map(BookResponse::from) call in the service converts each element and keeps the paging metadata. That is why the service returns Page<BookResponse> and never exposes entities.
What the response looks like
A Page serializes with the elements under content and the paging details beside it:
{
"content": [
{ "id": 11, "title": "Compilers", "author": "Aho" }
],
"pageable": { "pageNumber": 2, "pageSize": 5, "offset": 10, "paged": true, "unpaged": false,
"sort": { "sorted": true, "unsorted": false, "empty": false } },
"totalElements": 11,
"totalPages": 3,
"last": true,
"first": false,
"size": 5,
"number": 2,
"numberOfElements": 1,
"sort": { "sorted": true, "unsorted": false, "empty": false },
"empty": false
}totalElements and totalPages come from the count query. Clients use them to draw page controls.
Serializing Page safely
Serializing PageImpl directly produces JSON that Spring Data does not promise to keep stable. From Spring Data 3.3 onward, Spring logs a warning about it. You can choose a stable format in one of two ways.
The first way is to return PagedModel<BookResponse> from the controller. This gives a content array and a small page object:
@GetMapping
public PagedModel<BookResponse> list(Pageable pageable) {
return new PagedModel<>(service.list(pageable));
}The second way is to switch the whole application to the stable format in one place:
@Configuration
@EnableSpringDataWebSupport(pageSerializationMode = EnableSpringDataWebSupport.PageSerializationMode.VIA_DTO)
public class WebConfig {
}Either way, the JSON has the shape {"content": [...], "page": {"size": 5, "number": 2, "totalElements": 11, "totalPages": 3}}. Pick one and document it. Clients depend on this shape just as they depend on the BookResponse fields.
Setting defaults and limits
The default page size of 20 may not suit every endpoint. Use @PageableDefault on a parameter to set defaults for that endpoint only:
@GetMapping
public Page<BookResponse> list(
@PageableDefault(size = 10, sort = "title", direction = Sort.Direction.ASC) Pageable pageable) {
return service.list(pageable);
}Use @SortDefault when you need several default sort keys. Global settings go in application.properties:
spring.data.web.pageable.default-page-size=20
spring.data.web.pageable.max-page-size=100max-page-size matters. Its default is 2000, so a client can ask for size=2000 unless you lower it. A request above the maximum is clamped to the maximum. It is not rejected. Invalid values such as page=abc fall back to the defaults without an error.
Spring Data pages are zero-based. Setting spring.data.web.pageable.one-indexed-parameters=true makes the request parameter one-based, but the page.getNumber() value in the response stays zero-based. That mismatch confuses clients, so keep the default unless you have a strong reason.
Making sort order safe
Sorting by a client-supplied property name has two problems.
- A property that does not exist on the entity, such as
sort=isbn,asc, makes Spring Data throwPropertyReferenceException. Left unhandled, the client gets a 500 response instead of a 400. - A client can sort by any column, including unindexed ones. Sorting a large table by an unindexed column is slow.
The fix is an allow-list of sortable properties. First, add an exception for invalid sort keys:
public class InvalidSortException extends RuntimeException {
public InvalidSortException(String property) {
super("Cannot sort by '" + property + "'");
}
}Next, check the sort in the service before it reaches the repository. The service is a good place for this check because the rule applies to every caller:
private static final Set<String> SORTABLE = Set.of("id", "title", "author");
private void checkSort(Pageable pageable) {
for (Sort.Order order : pageable.getSort()) {
if (!SORTABLE.contains(order.getProperty())) {
throw new InvalidSortException(order.getProperty());
}
}
}
@Transactional(readOnly = true)
public Page<BookResponse> list(Pageable pageable) {
checkSort(pageable);
return repository.findAll(pageable).map(BookResponse::from);
}Finally, map the exception to a 400 response in ApiExceptionHandler, next to the not-found handler:
@ExceptionHandler(InvalidSortException.class)
public ProblemDetail handleInvalidSort(InvalidSortException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, ex.getMessage());
problem.setTitle("Invalid sort");
return problem;
}Now GET /api/books?sort=isbn returns a 400 with the same error format as the other failures.
Keeping page boundaries stable
ORDER BY title is not deterministic when two books share a title. The database may return tied rows in a different order for each query. A row can then appear on two pages or on none. This happens more often than you might expect, because PostgreSQL does not guarantee an order for tied rows.
The remedy is a unique tie-breaker as the last sort key. Add id to the end of whatever the client requested:
private Pageable withTieBreaker(Pageable pageable) {
Sort sort = pageable.getSort().and(Sort.by("id"));
return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sort);
}If you add this, call repository.findAll(withTieBreaker(pageable)) in the service. Be aware that Sort.and appends keys. If the client already sorts by id, the duplicate key is harmless.
Page, Slice, and the cost of counting
Page runs a count query on every request. On a large table, select count(*) can cost more than the data query itself. Spring Data skips the count in two cases: on the first page when fewer rows than size come back, and on later pages when the result is short. It cannot skip it otherwise.
| Return type | Count query | Knows total pages | Typical use |
|---|---|---|---|
| `Page<T>` | Yes | Yes | Admin screens with page numbers |
| `Slice<T>` | No (fetches `size + 1` rows) | No, only `hasNext()` | "Load more" and infinite scroll |
| `List<T>` with `Pageable` | No | No | When the client needs no metadata |
A repository can declare these types on derived queries, for example Slice<Book> findByAuthor(String author, Pageable pageable). Choose Slice when no one needs the total.
Offset pagination has another cost. offset 100000 makes the database walk past 100,000 rows before it returns any. Deep pages get slower, and rows inserted during browsing shift the pages. For very large or fast-changing data, keyset pagination (filtering by the last seen sort value) is the alternative. Spring Data supports it through ScrollPosition. Offset paging is fine for most CRUD applications.
Testing paging in the web layer
A @WebMvcTest can confirm that query parameters become a Pageable. Mock the service, capture the argument, and assert on it:
@WebMvcTest(BookController.class)
class BookControllerPagingTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private BookService service;
@Test
void passesPageAndSortToService() throws Exception {
Pageable requested = PageRequest.of(1, 5, Sort.by("title"));
when(service.list(any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(new BookResponse(6L, "Algorithms", "Knuth")), requested, 6));
mockMvc.perform(get("/api/books")
.param("page", "1")
.param("size", "5")
.param("sort", "title,asc"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content[0].title").value("Algorithms"));
ArgumentCaptor<Pageable> captor = ArgumentCaptor.forClass(Pageable.class);
verify(service).list(captor.capture());
assertThat(captor.getValue().getPageNumber()).isEqualTo(1);
assertThat(captor.getValue().getPageSize()).isEqualTo(5);
assertThat(captor.getValue().getSort().getOrderFor("title")).isNotNull();
}
}The test needs static imports from Mockito, MockMvcRequestBuilders, MockMvcResultMatchers, and AssertJ. The content path holds for the default Page format. If you switched to PagedModel or VIA_DTO, the elements are still under content, so this assertion works in all three setups.
To check the allow-list, test the service directly: call list with PageRequest.of(0, 5, Sort.by("isbn")) and expect InvalidSortException. A web test can then confirm the 400 with a mocked service that throws it.
Common errors
- 500 on
sort=isbn: the property is not on the entity. Add the allow-list and the 400 handler. - Duplicate or missing rows between pages: the sort has ties. Add
idas a tie-breaker. size=100000accepted:max-page-sizeis still 2000. Lower it.- Slow first request on a large table: the count query is the cause. Use
Sliceor reconsider whether the total is needed. - Warning about serializing
PageImpl: usePagedModelorVIA_DTO. - Off-by-one in a client: the client assumes pages start at 1, but the default is 0.
Exercise
A client requests GET /api/books?sort=title,asc&page=0&size=3 twice while no data changes. Several books share the title "Notes", and the second call returns them in a different order than the first. Why can this happen, and what is the smallest change to the service that prevents it?
Show answer
SQL does not define the order of rows that tie on the sort key, so the database may return "Notes" rows in any order, and rows can move across page boundaries. Append a unique key as the last sort key, for example pageable.getSort().and(Sort.by("id")), and pass a new PageRequest with the same page and size to repository.findAll.
Exercise
You change list to return Slice<BookResponse>. Which JSON fields can you no longer provide, and what do you gain?
Show answer
You can no longer provide totalElements or totalPages, because a Slice only knows whether a next slice exists (hasNext()). You gain the removal of the select count(*) query on every request, which helps on large tables.