Sub topic 12
Paginating and Sorting Collections
This chapter assumes you can write a @RestController, bind query parameters, and call a service layer. It builds on the GET /api/books endpoint from earlier chapters.
Why paginate
A collection endpoint that returns every row grows slower and larger as data grows. Clients get big payloads, and the server holds all rows in memory. Pagination returns one slice (a page) per request. Sorting makes the slices predictable, because a page only means something relative to an order.
The usual contract uses query parameters:
page: zero-based page index.size: number of items per page.sort: a property name, optionally followed by a direction, such assort=title,desc.
Doing it by hand with query parameters
You already know @RequestParam. Defaults and a cap keep the endpoint safe.
@GetMapping
public List<BookResponse> list(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
int safeSize = Math.min(Math.max(size, 1), 100);
int safePage = Math.max(page, 0);
return service.list(safePage, safeSize);
}Without the cap, a client can send size=1000000 and defeat the purpose of paging. Clamp the values at the controller or service boundary.
Using Spring Data's Pageable
If your service uses Spring Data (the spring-boot-starter-data-jpa dependency), Spring MVC can build a Pageable from the query string. Declare it as a method argument.
@GetMapping
public Page<BookResponse> list(
@PageableDefault(size = 20, sort = "title") Pageable pageable) {
return service.list(pageable);
}A request such as GET /api/books?page=1&size=10&sort=title,desc produces a Pageable for the second page of 10 items, sorted by title descending. Repeat sort to sort by several properties: sort=author&sort=title,desc.
The service passes the Pageable to a repository and maps entities to DTOs:
public interface BookRepository extends JpaRepository<Book, Long> {
}
@Service
public class BookService {
private final BookRepository repository;
public BookService(BookRepository repository) {
this.repository = repository;
}
public Page<BookResponse> list(Pageable pageable) {
return repository.findAll(pageable)
.map(b -> new BookResponse(b.getId(), b.getTitle(), b.getAuthor()));
}
}Page.map keeps the paging metadata and converts only the content, so entities never reach the JSON layer.
What the response looks like
Serializing a Page directly produces JSON with content, pageable, totalElements, totalPages, and more. Spring Data warns that the exact structure of its PageImpl serialization is not guaranteed to stay stable. Since Spring Data 3.3 you can enable a stable, documented format:
@Configuration
@EnableSpringDataWebSupport(pageSerializationMode = EnableSpringDataWebSupport.PageSerializationMode.VIA_DTO)
public class WebConfig {
}With VIA_DTO, the JSON contains a content array and a page object with size, number, totalElements and totalPages. If you need full control, define your own response record and copy those fields yourself.
Common errors
- Sorting by an unknown property.
sort=pricefails with aPropertyReferenceExceptionifBookhas nopricefield. The failure surfaces as a server error unless you handle it. Validate allowed sort fields, or translate the exception into a 400ProblemDetail. - Unbounded
size. Spring Data capssizeat 2000 by default. Lower it withspring.data.web.pageable.max-page-size=100. - Unstable order. Sorting by a non-unique column such as
authorcan return items in different order between requests, so items may repeat or vanish across pages. Add a unique tiebreaker such asid. - Exposing entities. Return DTOs, not JPA entities, even inside a
Page. - Counting cost.
Pageruns an extracountquery. If you do not need the total, returnSlice<T>, which only checks whether a next page exists.
spring.data.web.pageable.default-page-size=20
spring.data.web.pageable.max-page-size=100Exercise
A client calls GET /api/books?sort=author and reports that some books appear on two pages while others never appear. What is the likely cause, and how do you fix it?
Show answer
Many books share the same author, so the sort order among them is not deterministic and can differ between queries. Add a unique tiebreaker, for example sort=author&sort=id, or set a default sort such as @PageableDefault(sort = {"author", "id"}).
Exercise
Which return type avoids the extra count query when you only need to know whether another page exists: Page<T> or Slice<T>?
Show answer
Slice<T>. It fetches one extra row to detect a next page and skips the count query that Page<T> runs.