Sub topic 13
Paginating and sorting collections
This chapter assumes you have a working BookRepository, BookService, and BookController from earlier chapters. You should also know what a Pageable is at a basic level and how Spring MVC binds query parameters. Here you will see how the list endpoint returns one page of books at a time, in a requested order.
Why not return everything
A GET /api/books that returns every row works with ten books. With a million rows it uses a lot of memory, takes a long time to serialize, and can time out. Pagination limits each response to a fixed number of rows. Sorting makes that slice predictable, because a database gives no guaranteed row order unless you ask for one.
What the code already does
The service and controller from earlier chapters already support paging. The relevant parts are:
// BookRepository: JpaRepository already extends PagingAndSortingRepository
public interface BookRepository extends JpaRepository<Book, Long> {
}
// BookService
@Transactional(readOnly = true)
public Page<BookResponse> list(Pageable pageable) {
return repository.findAll(pageable).map(BookResponse::from);
}
// BookController
@GetMapping
public Page<BookResponse> list(Pageable pageable) {
return service.list(pageable);
}No extra repository code is needed. findAll(Pageable) is inherited from JpaRepository. The Pageable argument in the controller is filled in by Spring Data's web support, which Spring Boot enables automatically when Spring Data and Spring Web are both present.
The query parameters
Spring reads three parameters from the URL.
| Parameter | Meaning | Default |
|---|---|---|
| `page` | Zero-based page number | `0` |
| `size` | Rows per page | `20` |
| `sort` | `property,direction`, repeatable | unsorted |
Some examples:
GET /api/booksreturns the first 20 books.GET /api/books?page=2&size=5returns books 11 to 15.GET /api/books?sort=title,ascsorts by title.GET /api/books?sort=author,desc&sort=titlesorts by author descending, then by title ascending.
Page numbers start at 0, which surprises many clients. A request for page=1 is the second page.
What the response looks like
findAll returns a Page, which carries the rows and the counts. A response for ?page=0&size=2 looks like this, shortened:
{
"content": [
{ "id": 1, "title": "Dune", "author": "Frank Herbert" },
{ "id": 2, "title": "Emma", "author": "Jane Austen" }
],
"pageable": { "pageNumber": 0, "pageSize": 2 },
"totalElements": 7,
"totalPages": 4,
"last": false
}To produce totalElements, Hibernate runs a second select count(*) query next to the page query. On large tables that count can be slow. If clients only need "next page" navigation, returning a Slice skips the count query. A repository method such as Slice<Book> findBy(Pageable pageable) does this.
Recent Spring Data versions log a warning when a PageImpl is serialized directly, because its JSON shape is not a stable contract. For a public API, consider wrapping the page in your own record or using Spring Data's PagedModel. That keeps the response format under your control, the same reason you use DTOs.
Setting defaults and limits
Without a cap, a client can ask for size=1000000. Spring Data limits size to 2000 by default. You can set your own defaults in application.properties:
spring.data.web.pageable.default-page-size=10
spring.data.web.pageable.max-page-size=50A request above the maximum is reduced to 50 and is not rejected. You can set a default sort for one endpoint with @PageableDefault:
@GetMapping
public Page<BookResponse> list(
@PageableDefault(size = 10, sort = "title") Pageable pageable) {
return service.list(pageable);
}Common errors
- Sorting by a name that is not an entity property.
?sort=namefails with aPropertyReferenceException, which becomes a 500 response unless you handle it. Thesortvalue must match a field ofBook, such astitle, not a JSON field of the DTO. If the two differ, translate names before building thePageable. - Paging without a sort. Page boundaries can shift or repeat rows between requests when the order is undefined. Always set a default sort.
- Assuming pages start at 1. They start at 0.
- Exposing every property as sortable. Sorting on an unindexed column over a large table is slow. Restrict sorting to indexed fields when the table is big.
Exercise
A client calls GET /api/books?page=3&size=10&sort=name,asc, but Book has the fields title and author. What happens, and how do you stop it from returning a 500 error?
Show answer
Spring Data cannot find a property called name on Book, so it throws a PropertyReferenceException, which becomes a 500 response by default. Fix it by adding an @ExceptionHandler in the @RestControllerAdvice class that returns a 400 ProblemDetail, or by checking the requested sort properties against an allow-list before calling the repository.
Exercise
Which parameter combination returns books 21 to 30 in title order?
Show answer
?page=2&size=10&sort=title,asc. Pages are zero-based, so page 2 with size 10 skips the first 20 rows.