Pagination and dynamic filters in Spring: Pageable, Page, Slice and JPA Specifications
Paginating with Pageable and @PageableDefault, Page versus Slice, zero- or one-based pages, capping size and rejecting unknown sort fields; filtering products by brand, purpose and price range with Specifications and the JPA metamodel; grouping OR correctly, keeping filters in the URL, and the LIKE, count-query and fetch-join traps. With a Spring Boot 3 lab verified by tests.
On this page
1. The problem
/products loads the whole table to show 12 products. The fix uses @RequestParam int page: no ?page= means a 400. Filters written as query methods turn 3 optional criteria into 2³ = 8 methods, and ?sort=passwordHash returns a 500.
2. Key idea
Like a phone book: Pageable is the page number and rows per page; **Specification**s are transparent filters stacked on top of each other, and unused ones are pulled out.
Paging fetches one page with LIMIT (rows) and OFFSET (rows skipped). The page lives in the query string, so bookmarks and the Back button work. OFFSET 100000 still reads and discards 100,000 rows: infinite feeds and export APIs use keyset pagination (WHERE id < :lastId ORDER BY id DESC LIMIT 12).
| Return type | SQL run | Use when | Don't use when |
|---|---|---|---|
Page<T> |
the page + select count(*) |
numbered page links 1 2 3 | big tables where counting is expensive |
Slice<T> |
one query fetching size + 1 rows |
"load more", infinite scroll | you need the total pages |
| Keyset | WHERE id < :last |
deep pages, exports | jumping straight to page 37 |
2.1 What do you write dynamic filters with?
| Approach | Use when | Don't use when |
|---|---|---|
Query methods, @Query JPQL |
fixed conditions | optional criteria: method explosion |
| Specification | dynamic filters on one entity | complex joins, projections |
| QueryDSL | many dynamic, type-safe queries | you don't want another library and code generation |
A Specification<T> is a function (root, query, cb) -> Predicate (jakarta.persistence.criteria.Predicate, evaluated in the DB). The repository also extends JpaSpecificationExecutor<T> to get findAll(spec, pageable). The metamodel Product_ is generated at compile time: renaming a field breaks compilation, rather than failing at runtime like root.get("price").
3. In Java
public static Specification<Product> factoryIn(Collection<String> factories) {
if (factories == null || factories.isEmpty()) return null; // null = no filter
return (root, query, cb) -> root.get(Product_.factory).in(factories);
}
public static Specification<Product> priceInAnyRange(List<PriceRange> ranges) { // OR inside ONE spec
if (ranges == null || ranges.isEmpty()) return null;
return (root, query, cb) -> cb.or(ranges.stream()
.map(r -> r.max() == null ? cb.greaterThanOrEqualTo(root.get(Product_.price), r.min())
: cb.between(root.get(Product_.price), r.min(), r.max()))
.toArray(Predicate[]::new));
}
private static final Set<String> SORTABLE = Set.of("price", "name", "id");
static Pageable safeSort(Pageable p) {
Sort sort = Sort.by(p.getSort().stream().filter(o -> SORTABLE.contains(o.getProperty())).toList());
return PageRequest.of(p.getPageNumber(), p.getPageSize(), sort.and(Sort.by("id"))); // id last: stable order
}
// Specification.allOf(nameContains(f.q()), factoryIn(f.factory()), priceInAnyRange(f.priceRanges()))
// SQL: where p.factory in (?,?) and (p.price between ? and ? or p.price >= ?)Price ranges arrive as slugs (10-15-trieu) and are looked up in a PriceRange enum; unknown slugs are dropped, never split and parseInted.
Pageable configuration, filter-preserving links and joins in Specifications
spring.data.web.pageable.one-indexed-parameters=truemakes?page=1the first page, butPage.getNumber()still counts from 0: views must add 1.max-page-size=50caps?size=100000at 50.- Links to other pages must keep the filters; changing a filter goes back to page 1. Thymeleaf:
@{/products(page=${i}, factory=${filter.factory}, sort=${param.sort})}. - Empty tables:
totalPages = 0, and#numbers.sequence(1, 0)counts down to 1, 0. Wrap the pager inth:if="${page.totalPages > 0}". - 1-to-n joins in a Specification multiply rows: add
query.distinct(true). A fetch join with paging makes Hibernate page in memory (warning HHH90003004). LIKE '%tuf%'can't use a B-tree index; at millions of rows you need full-text,pg_trgmor Elasticsearch. Escape%and_in the search term.- Declare
hibernate-jpamodelgeninannotationProcessorPathswith${hibernate.version}, not a hard-coded version.
4. Working with AI
Delegate to AI: each Specification function, the filter record, tests for every filter combination.
Check yourself:
- Takes a
Pageable, not@RequestParam int page;max-page-sizeis set. - Sort columns go through a whitelist, always ending with
id. - Multiple price ranges are ORed inside one Specification, with correct parentheses in the SQL log.
- Filter values are looked up in an enum or finite set, not parsed freely.
- 1-to-n joins use
distinct; no fetch joins with paging.
5. Exercises
Exercise 1: Review an AI-written price-range filter
AI chained Specification.where(factoryIn(f)).and(range1).or(range2), describing it as "filter by brand and two price ranges". With factory=APPLE and the ranges 10–15 million and over 20 million, a 25-million Dell laptop shows up. Why? Name a test and fix it.
Solution to Exercise 1
- The
.and().or()chain producesfactory IN ('APPLE') AND r1 OR r2: AND binds tighter than OR, so every product over 20 million from any brand matches. - Test: data with a 25-million MacBook and a 25-million Dell; filter
factory=APPLE&price=10-15-trieu,tren-20-trieu; expect only the MacBook. - Fix: gather the ranges into one Specification with
cb.or(...), thenallOf(factoryIn(f), priceInAnyRange(ranges)); check the SQL log has parentheses around the two ranges.
Exercise 2: Page or Slice?
(a) An admin orders page, 2 million rows, where admins need "page 3 of 1,240". (b) A mobile app scrolling a product feed. (c) A nightly job exporting every order to CSV. Choose the paging approach for each.
Solution to Exercise 2
- (a)
Page, but counting 2 million rows every time is expensive: cache the total for a few minutes, or show "more than 10,000 results" past a threshold. - (b)
Sliceor keyset: no total needed, only "is there more"; keyset doesn't repeat rows when new products are inserted. - (c) Keyset on
id: deepOFFSETs get slower and repeat or skip rows when data changes between batches.
Summary
Pageablein,PageorSliceout; capsize.Pageaddscount(*);Slicefetchessize + 1; deep pages use keyset.- One Specification per criterion, returning
nullwhen empty, combined withallOf. - OR the price ranges inside one Specification before ANDing.
- Sort columns and filter values go through whitelists.
Further reading: ORM and JPA part 2.
Practice interview questions on this topic
- How does pagination work in Spring Data? How is Page different from Slice?
- What is a JPA Specification, how does it differ from query methods, and how do you use it for dynamic filters?
- A list page with LIKE search and pagination gets slow on a large table. How do you fix it?
- How does @EntityGraph differ from JOIN FETCH? What goes wrong when fetching several collections at once?
All JPA & Hibernate questions →All SQL & Query Tuning questions →
Comments
Community rules