Sub topic 12
Paginating and sorting collections
This chapter assumes you can write a @RestController with @GetMapping, read query parameters, and call a service layer. It also assumes you know basic Spring Data JPA repositories. You will add paging and sorting to the book list endpoint and see where the defaults can hurt you.
Why collections need paging
An endpoint like GET /api/books that returns every row works while the table has 50 rows. At 5 million rows it exhausts memory, slows the database, and sends a response the client cannot use. Paging puts a bound on each response. Sorting makes the pages predictable, because without an order the database can return rows in any order.
Spring splits this job into three parts:
- Spring Data Commons defines
Pageable(page number, page size, sort) andPage<T>(the content plus counts). - Spring Data web support is auto-configured by Spring Boot. It turns the query parameters
page,sizeandsortinto aPageablemethod argument. - Your repository accepts a
Pageableand runs the limited, ordered query.
The request flow
Accepting a Pageable
Declare a Pageable parameter and Spring fills it in. Use @PageableDefault to set values for requests that omit the parameters.
@GetMapping
public PageResponse<BookResponse> list(
@RequestParam(defaultValue = "") String title,
@PageableDefault(size = 20, sort = "title") Pageable pageable) {
return service.search(title, pageable);
}The client controls the three inputs through these parameters:
| Parameter | Meaning | Default | Column |
|---|---|---|---|
| `page` | Zero-based page index | 0 | |
| `size` | Items per page | 20 | |
| `sort` | `property[,asc\ | desc]`, repeatable | unsorted |
A request such as GET /api/books?page=2&size=10&sort=author,asc&sort=title,desc sorts by author ascending, then by title descending, and returns the third page of ten items. Order of the sort parameters matters: the first is the primary key.
The repository and service
A Spring Data repository method that takes a Pageable and returns Page<T> runs two queries: one for the page content and one count query for the total.
public interface BookRepository extends JpaRepository<Book, Long> {
Page<Book> findByTitleContainingIgnoreCase(String title, Pageable pageable);
}The service converts entities to DTOs. Page.map keeps the paging metadata while transforming the content.
@Service
public class BookService {
private final BookRepository repository;
public BookService(BookRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public PageResponse<BookResponse> search(String title, Pageable pageable) {
Page<BookResponse> page = repository
.findByTitleContainingIgnoreCase(title, pageable)
.map(book -> new BookResponse(book.getId(), book.getTitle(), book.getAuthor()));
return PageResponse.from(page);
}
}Define your own page response
You can return Page<BookResponse> from the controller, and it serializes. Do not rely on that for a public API. The JSON shape of PageImpl is not a supported contract, and Spring Data warns about this from version 3.3. Define a small record so the JSON you publish is yours.
public record PageResponse<T>(
List<T> items,
int page,
int size,
long totalElements,
int totalPages) {
public static <T> PageResponse<T> from(Page<T> page) {
return new PageResponse<>(
page.getContent(),
page.getNumber(),
page.getSize(),
page.getTotalElements(),
page.getTotalPages());
}
}A response then looks like this:
{
"items": [
{ "id": 7, "title": "Dune", "author": "Frank Herbert" }
],
"page": 0,
"size": 20,
"totalElements": 1,
"totalPages": 1
}Configuring limits
The defaults are generous. In Spring Boot the maximum page size is 2000, which means one request can still load 2000 rows. Set limits that match your data.
spring.data.web.pageable.default-page-size=20
spring.data.web.pageable.max-page-size=100When a client asks for size=5000, Spring does not fail. It clamps the size to the maximum. Malformed values such as page=abc also fall back to defaults and do not produce a 400 response. If you need strict rejection, take int page and int size as validated @RequestParam values and build the PageRequest yourself.
Other useful properties:
spring.data.web.pageable.one-indexed-parameters=truemakespage=1the first page. ThePageobject still reports zero-based numbers, so your response can be confusing if you enable it. Pick one convention and document it.spring.data.web.pageable.page-parameterandsize-parameterrename the parameters.spring.data.web.sort.sort-parameterrenamessort.
Protect your sort fields
The sort value is a property name taken from the client and passed to the query. A request with sort=doesNotExist makes Spring Data throw a PropertyReferenceException, which becomes a 500 unless you handle it. A client can also sort by a property you did not intend to expose, such as a column without an index, which slows the query for everyone.
Check sort properties against an allow-list before running the query:
private static final Set<String> SORTABLE = Set.of("title", "author", "id");
private Pageable validated(Pageable pageable) {
pageable.getSort().forEach(order -> {
if (!SORTABLE.contains(order.getProperty())) {
throw new InvalidSortException(order.getProperty());
}
});
return pageable;
}Define InvalidSortException as a RuntimeException and map it to a 400 ProblemDetail in your @RestControllerAdvice, as in the earlier chapter on error handling. Call validated(pageable) at the start of search.
Gotchas and edge cases
- Unstable order. If you sort by a column with duplicate values, such as
author, rows with equal values can move between pages across requests. Clients then see duplicates or miss items. Add a unique tie-breaker, for examplesort=author,asc&sort=id,asc, or appendidto the sort in the service. - Pages beyond the end.
page=999on a table with three pages returns a normal 200 with an emptyitemslist and the truetotalElements. Do not turn this into a 404 unless your API contract says so. - The count query.
Page<T>always runs a count. On large tables, counting can cost more than fetching the page. If the client only needs a "next page" link, returnSlice<T>instead. ASlicefetches one extra row to learn whether another page exists and skips the count. - Deep offsets. Offset paging makes the database scan and discard all skipped rows, so
page=50000is slow. For feeds and exports, consider keyset paging: filter withwhere id > :lastId order by id limit :size. Spring Data supports this throughScrollPositionandWindow<T>, but it needs a stable, unique sort key and does not allow jumping to an arbitrary page. - Joins with collections. A fetch join to a collection combined with paging makes Hibernate page in memory, with a warning in the log. Page the parent IDs first, or avoid fetching the collection in the paged query.
- Sorting the DTO name.
sortrefers to entity property names, not the JSON field names of your DTO. If the two differ, translate them in the service.
Testing the binding
In a @WebMvcTest you can check that query parameters reach the service as a correctly built Pageable. Capture the argument and assert on it.
@WebMvcTest(BookController.class)
class BookControllerPagingTest {
@Autowired
MockMvc mockMvc;
@MockitoBean
BookService service;
@Test
void bindsPageSizeAndSort() throws Exception {
when(service.search(any(), any()))
.thenReturn(new PageResponse<>(List.of(), 2, 10, 0, 0));
mockMvc.perform(get("/api/books")
.param("page", "2")
.param("size", "10")
.param("sort", "title,desc"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.page").value(2));
ArgumentCaptor<Pageable> captor = ArgumentCaptor.forClass(Pageable.class);
verify(service).search(eq(""), captor.capture());
Pageable pageable = captor.getValue();
assertThat(pageable.getPageNumber()).isEqualTo(2);
assertThat(pageable.getPageSize()).isEqualTo(10);
assertThat(pageable.getSort().getOrderFor("title").getDirection())
.isEqualTo(Sort.Direction.DESC);
}
}Choosing an approach
| Need | Use |
|---|---|
| Numbered pages with a total count | `Page<T>` and offset paging |
| "Load more" with no total | `Slice<T>` |
| Large or fast-changing data, infinite feeds | Keyset paging with `Window<T>` |
| A fixed, documented JSON shape | Your own `PageResponse` record |
Exercise
A client calls GET /api/books?sort=author&page=0&size=10 and then page=1. Some books appear on both pages. What is the likely cause, and how do you fix it?
Show answer
Many books share the same author, so the database may order those ties differently from one query to the next. Rows can then move across the page boundary. Fix it by adding a unique tie-breaker to the sort, such as id: sort=author,asc&sort=id,asc, or by appending id to the sort in the service.
Exercise
Your endpoint accepts a Pageable. A client sends size=100000. Spring Boot is configured with spring.data.web.pageable.max-page-size=100. What does the endpoint do?
Show answer
It does not reject the request. Spring clamps the size to 100 and returns a normal 200 response with at most 100 items. The size field in your PageResponse shows 100, so the client can see the effective value.