Sub topic 10
Pagination and Sorting
This chapter assumes you can write a Spring Data repository, know derived query methods and @Query, and have the Book and Author entities from earlier chapters. You should also know basic SQL ORDER BY, LIMIT and OFFSET.
Loading every row of a large table into memory is slow and often fatal. Spring Data JPA gives you two small abstractions for this: Sort for ordering and Pageable for choosing one slice of the result.
The Core Types
| Type | Purpose |
|---|---|
| `Sort` | Describes one or more properties and their direction. |
| `Pageable` | Describes a page number, a page size and an optional `Sort`. |
| `PageRequest` | The usual implementation of `Pageable`. |
| `Page<T>` | The content of one page plus the total number of elements and pages. |
| `Slice<T>` | The content of one page plus whether a next page exists. It has no total. |
| `List<T>` | Just the content. The paging parameters are applied but no metadata is returned. |
Page numbers are zero-based. PageRequest.of(0, 10) is the first page of ten elements.
Sorting
A Sort names entity properties, not column names. Use the Java field names, for example publishedYear rather than published_year.
import org.springframework.data.domain.Sort;
public class SortExamples {
public static void main(String[] args) {
Sort byYear = Sort.by("publishedYear");
Sort newestFirst = Sort.by(Sort.Direction.DESC, "publishedYear");
Sort combined = Sort.by(
Sort.Order.desc("publishedYear"),
Sort.Order.asc("title").ignoreCase());
System.out.println(byYear);
System.out.println(newestFirst);
System.out.println(combined);
}
}The combined sort orders by year descending and breaks ties by title ascending, ignoring case. Add a repository method that takes a Sort as its last parameter:
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface BookSortRepository extends JpaRepository<Book, Long> {
List<Book> findByPublishedYearGreaterThanEqual(int year, Sort sort);
}You can also write the order into the method name with OrderBy. That fixes the order at compile time:
List<Book> findByPublishedYearGreaterThanEqualOrderByTitleAsc(int year);Use a Sort parameter when the caller chooses the order. Use OrderBy when the order is part of the meaning of the query.
Paging with Pageable
Declare a Pageable parameter and choose a return type. The BookRepository from the earlier chapter already has this method:
Page<Book> findByPublishedYearGreaterThanEqual(int year, Pageable pageable);A service can call it like this:
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
@Service
public class BookListingService {
private final BookRepository books;
public BookListingService(BookRepository books) {
this.books = books;
}
public Page<Book> recentBooks(int pageNumber) {
Pageable pageable = PageRequest.of(
pageNumber, 20, Sort.by("publishedYear").descending().and(Sort.by("id")));
return books.findByPublishedYearGreaterThanEqual(2000, pageable);
}
}The id at the end of the sort is deliberate. See the section on stable ordering below.
A Pageable already contains a Sort. Do not pass both a Pageable and a Sort to the same method.
What Page Exposes
Page<Book> page = service.recentBooks(0);
List<Book> content = page.getContent();
long totalElements = page.getTotalElements();
int totalPages = page.getTotalPages();
boolean hasNext = page.hasNext();
Pageable next = page.nextPageable();Page, Slice or List
A Page return type causes a second query. Spring Data runs the page query with LIMIT and OFFSET, then runs a select count(...) with the same conditions to fill getTotalElements(). On a large table the count can cost more than the page itself.
If the client only needs a "load more" button, return Slice<Book>. Spring Data asks the database for one extra row (page size plus one) to detect whether a next page exists, and it skips the count query. If you do not need any metadata, return List<Book>.
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
Slice<Book> findByTitleContainingIgnoreCase(String text, Pageable pageable);Note that a derived method like findByTitleContainingIgnoreCase can return List, Slice or Page depending on the signature you declare. Do not declare overloads that differ only in return type, because Java does not allow that. Give each variant its own method name.
Paging in Custom Queries
@Query methods accept Pageable too. For JPQL, Spring Data appends the ORDER BY from the Sort and derives a count query from your query.
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
@Query("select b from Book b where b.author.name = :name")
Page<Book> findByAuthorNamePaged(@Param("name") String name, Pageable pageable);Two situations need extra care.
- Native queries. Spring Data cannot reliably rewrite native SQL, so you supply the count query yourself with
countQuery. Dynamic sorting in native queries is limited, so prefer fixedORDER BYclauses there. - Queries with
join fetch. A collection join fetch combined with paging cannot be done in SQL without returning duplicate parent rows. Hibernate then fetches everything and paginates in memory, and logs a warning (HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory). Avoid this. Page the parent entities first, then load the collections for those ids in a second query, or rely on batch fetching.
A fetch join on a many-to-one association, such as Book.author, is safe with paging because it does not multiply rows. For that case, give the count query explicitly because the join fetch is not valid in a select count:
@Query(
value = "select b from Book b join fetch b.author where b.publishedYear >= :year",
countQuery = "select count(b) from Book b where b.publishedYear >= :year")
Page<Book> findRecentWithAuthor(@Param("year") int year, Pageable pageable);Stable Ordering
SQL does not guarantee any row order unless you ask for one. If you page without a sort, or sort by a column with duplicate values, the database may return tied rows in a different order on each query. A row can then appear on two pages or on none.
The fix is to end every sort with a unique property, normally the id, as the service above does. A sort like publishedYear desc, id asc is total, so every page boundary is well defined.
Pageable stable = PageRequest.of(0, 20,
Sort.by(Sort.Order.desc("publishedYear"), Sort.Order.asc("id")));Limiting Without Paging
For "the first N" queries you do not need Pageable. Use First or Top in the method name:
List<Book> findTop5ByOrderByPublishedYearDesc();
Optional<Book> findFirstByAuthorNameOrderByPublishedYearDesc(String name);Using Pageable in a Controller
In a Spring MVC controller, Spring Data's web support can build a Pageable from request parameters page, size and sort. Spring Boot enables this when Spring Data web support is on the classpath.
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BookController {
private final BookRepository books;
public BookController(BookRepository books) {
this.books = books;
}
@GetMapping("/books")
public Page<BookSummary> list(@RequestParam(defaultValue = "1900") int fromYear,
Pageable pageable) {
return books.findByPublishedYearGreaterThanEqual(fromYear, pageable)
.map(b -> new BookSummary(b.getId(), b.getTitle()));
}
public record BookSummary(Long id, String title) {
}
}A request such as /books?page=0&size=10&sort=title,asc yields the matching Pageable. Two points matter in practice:
- Clients choose the sort property. An unknown property causes an error, and a sort on an unindexed column can be slow. Restrict the allowed properties if the endpoint is public.
- Boot caps the page size at 2000 by default (
spring.data.web.pageable.max-page-size). Set a lower limit for public endpoints and a sensible default (spring.data.web.pageable.default-page-size, which is 20).
Returning Page<Entity> directly as JSON also exposes your entity structure. The example maps to a record with Page.map, which keeps the paging metadata. Recent Spring Data versions warn that serializing PageImpl directly is not a stable JSON format, so consider PagedModel for public APIs.
Offset Pagination Limits
Offset paging has two weaknesses:
- Deep pages are slow. The database still walks past all skipped rows, so
OFFSET 1000000costs about as much as reading a million rows. - Results shift when rows are inserted or deleted between requests, so a client may see a duplicate or miss an item.
Spring Data JPA supports keyset (scroll) pagination in recent versions through Window<T> and ScrollPosition. A derived method returns a window and the caller continues from the last position:
import org.springframework.data.domain.Limit;
import org.springframework.data.domain.ScrollPosition;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Window;
Window<Book> findByPublishedYearGreaterThanEqual(
int year, ScrollPosition position, Limit limit, Sort sort);You would call it first with ScrollPosition.keyset(), then with window.positionAt(window.size() - 1) for the next window. This needs Spring Data 3.1 or later, and the sort must include a unique property.
Testing Paging
A @DataJpaTest can check both content and metadata.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest
class BookPagingTest {
@Autowired
private AuthorRepository authors;
@Autowired
private BookRepository books;
@Test
void returnsSecondPageInStableOrder() {
Author author = new Author("Test Author");
for (int i = 1; i <= 5; i++) {
author.addBook(new Book("Book " + i, 2000));
}
authors.save(author);
Page<Book> page = books.findByPublishedYearGreaterThanEqual(
2000, PageRequest.of(1, 2, Sort.by("title")));
assertThat(page.getTotalElements()).isEqualTo(5);
assertThat(page.getTotalPages()).isEqualTo(3);
assertThat(page.getContent()).extracting(Book::getTitle)
.containsExactly("Book 3", "Book 4");
}
}All five books share the same year, so the test sorts by title, a unique value here, to make the expected page predictable.
Exercise
A client pages through findByPublishedYearGreaterThanEqual(2000, PageRequest.of(n, 20, Sort.by("publishedYear"))) and sometimes sees the same book on two pages. Why does this happen, and how do you fix it?
Show answer
Many books share the same publishedYear, so the sort does not fully determine the order. The database may order tied rows differently on each query, so a row can cross a page boundary. Add a unique property to the sort, for example Sort.by("publishedYear").and(Sort.by("id")).
Exercise
An endpoint only needs to show a "Load more" button and never displays the total number of results. Which return type should the repository method use, and what does it save?
Show answer
Slice<Book>. Spring Data fetches one extra row to learn whether a next page exists and skips the select count query that a Page return type requires.