Sub topic 10
Pagination and sorting
This chapter assumes you can write a derived query method and know what a Pageable parameter looks like in a repository signature. It also assumes you know basic SQL (order by, limit, offset). Here you will learn how Spring Data JPA returns part of a result set, how it sorts, and which mistakes cause slow or unstable pages.
Why page at all
A query such as findAll() loads every row into memory. This works with 50 rows and fails with 5 million. Pagination asks the database for one slice at a time. Sorting makes that slice predictable.
Pageable, Page and Sort
Spring Data uses three types:
Sortdescribes one or more properties and a direction.Pageablecombines a page number (starting at 0), a page size and an optionalSort. You usually create it withPageRequest.of(...).Page<T>holds the content of one page plus the total number of elements and pages.
Any repository method can accept a Pageable or a Sort as its last parameter. The BookRepository from earlier chapters already has one:
Page<Book> findByPublishedYearGreaterThanEqual(int year, Pageable pageable);Using a page
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
Pageable pageable = PageRequest.of(0, 20, Sort.by("publishedYear").descending()
.and(Sort.by("title")));
Page<Book> page = books.findByPublishedYearGreaterThanEqual(1970, pageable);
System.out.println(page.getContent().size());
System.out.println(page.getTotalElements());
System.out.println(page.getTotalPages());
System.out.println(page.hasNext());This sorts by year, newest first, and then by title. Sort property names refer to entity fields, not column names. publishedYear is correct. A column name such as published_year fails at runtime.
What Hibernate runs
For a Page, Spring Data runs two statements. The first selects the rows with order by and a limit. The second is a select count(...) with the same filter, which supplies the total.
placeholderThe count query costs time on large tables. You can avoid it by choosing a different return type.
| Return type | Count query | Knows total | Use when |
|---|---|---|---|
| `Page<T>` | Yes | Yes | The UI shows page numbers |
| `Slice<T>` | No | Only whether a next slice exists | "Load more" or infinite scroll |
| `List<T>` | No | No | You only need the rows |
Slice<T> fetches one extra row to learn whether another slice exists. A List<T> with a Pageable parameter also works and skips the count.
Common errors
- Unstable order. If you sort by a non-unique property such as
publishedYear, rows with equal values can move between pages. Add a unique tie-breaker such asid. - Paging with a collection join fetch. A
join fetchon a collection combined with aPageablemakes Hibernate paginate in memory and log warning HHH90003004. Page the parent entities first, or fetch the collection in a second query. - Count query for custom queries. For a complex
@QueryreturningPage, supplycountQueryyourself so the count does not inherit a fetch join. - Large offsets. Page 50,000 forces the database to skip many rows. For deep browsing, consider keyset (seek) pagination.
Exercise
A screen shows "Load more" and never displays the total count. Which return type should the repository method use, and why?
Show answer
Use Slice<Book>. It skips the count query and still reports through hasNext() whether another slice exists.