Practice: pagination, sorting and searching
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
A list screen that works with 14 products can fail with 2 lakh: slow pages, repeated rows, huge page sizes and wrong totals. Each mistake below shows the real output and the fix.
Mistake 1: paging a collection fetch join
Paging a collection fetch join (join fetch o.items with a Pageable) asks for a page of orders from SQL that has one row per item.
WARN org.hibernate.orm.query : HHH90003004: firstResult/maxResults specified with collection fetch; applying in memoryDEBUG org.hibernate.SQL : select o1_0.order_id,o1_0.customer_id,o1_0.address_id,i1_0.order_id,i1_0.order_item_id,i1_0.product_id,i1_0.quantity,i1_0.unit_price,o1_0.ordered_at,o1_0.status from orders o1_0 join order_items i1_0 on o1_0.order_id=i1_0.order_id order by o1_0.order_idExample 1 · lab/FetchJoinPagingDemo.java: a collection fetch join with a page (Spring Boot 4.1)
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.lab;
import org.springframework.data.domain.Page;import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Sort;import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.order.Order;import com.shoplite.order.OrderRepository;
@Component("fetchpage")class FetchJoinPagingDemo implements LabDemo {
private final OrderRepository orders;
FetchJoinPagingDemo(OrderRepository orders) { this.orders = orders; }
@Override @Transactional(readOnly = true) public void run() { // Page 0, 3 orders, each with ALL its items (a collection fetch join) Page<Order> page = orders.findAllWithItems(PageRequest.of(0, 3, Sort.by("id"))); for (Order order : page) { System.out.println("Order " + order.getId() + ": " + order.getItems().size() + " items"); } System.out.println("total=" + page.getTotalElements()); }}$ java -jar target/page-lab-0.1.0.jar --demo=fetchpage DEBUG org.hibernate.SQL : select o1_0.order_id,o1_0.customer_id,o1_0.address_id,i1_0.order_id,i1_0.order_item_id,i1_0.product_id,i1_0.quantity,i1_0.unit_price,o1_0.ordered_at,o1_0.status from (select o1_0.order_id,o1_0.customer_id,o1_0.address_id,o1_0.ordered_at,o1_0.status from orders o1_0 where exists(select 1 from order_items i1_0 where o1_0.order_id=i1_0.order_id) order by o1_0.order_id limit ?,?) o1_0(order_id,customer_id,address_id,ordered_at,status) join order_items i1_0 on o1_0.order_id=i1_0.order_id order by o1_0.order_id DEBUG org.hibernate.SQL : select count(o1_0.order_id) from orders o1_0 Order 1: 2 items Order 2: 3 items Order 3: 2 items total=16
What this code does
- Spring Boot 4.1 (Hibernate 7.4): the
limit ?,?sits in a subquery overorders, so each order keeps all its items. - The same method on Spring Boot 3 reads every row and pages in memory (the log above the example).
- Either way the safe pattern is: page the orders first, then fetch their items for just that page.
Hibernate 6 (Spring Boot 3) cannot put a LIMIT on that, so it loads every order and item, logs HHH90003004 and pages in memory, as the log shows. Hibernate 7.4 (Spring Boot 4.1) on MySQL pages the orders in a subquery first (the example). The SQL is long, and it still breaks when you filter on the fetched collection, so do not rely on it.
Fix: page the parents (or their ids) without the fetch join, then load the children for just that page. Use a countQuery that counts parents.
Mistake 2: sorting without a unique tiebreaker
An unstable sort orders by a column with equal values (status, category, price) and nothing else. Tied rows may come back in any order, even a different one for page 0 and page 1.
Example 2 · Equal sort values without and with a tiebreaker (MySQL)
Runs in: MySQL 8.4 (a scratch database named practice)
mysql -u root -p -B practice -e "SET cte_max_recursion_depth = 5000;CREATE TABLE test_orders (id INT AUTO_INCREMENT PRIMARY KEY, status VARCHAR(10), note VARCHAR(200));INSERT INTO test_orders (status, note) WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 3000) SELECT ELT(1 + i % 3, 'PLACED', 'SHIPPED', 'DELIVERED'), REPEAT('x', 100) FROM n;SELECT GROUP_CONCAT(id) AS page_0 FROM (SELECT id FROM test_orders ORDER BY status LIMIT 10) p;SELECT GROUP_CONCAT(id) AS page_1 FROM (SELECT id FROM test_orders ORDER BY status LIMIT 10 OFFSET 10) p;SELECT GROUP_CONCAT(id) AS page_0 FROM (SELECT id FROM test_orders ORDER BY status, id LIMIT 10) p;SELECT GROUP_CONCAT(id) AS page_1 FROM (SELECT id FROM test_orders ORDER BY status, id LIMIT 10 OFFSET 10) p;"Enter password: page_0 26,2,29,17,5,14,8,20,23,11 page_1 56,26,14,59,38,17,44,23,20,47 page_0 2,5,8,11,14,17,20,23,26,29 page_1 32,35,38,41,44,47,50,53,56,59
What this code does
- 3000 orders, 1000 per status. Sorted only by
status, page 0 and page 1 both contain orders 26, 14, 17, 20 and 23, and orders such as 32 and 35 appear on neither page. - With
ORDER BY status, idevery row has one fixed place: page 0 holds ids 2 to 29 and page 1 continues with 32 to 59, no overlap. - Your ids may differ with another MySQL version or settings; the overlap without a tiebreaker is the point. Run it in a scratch
practicedatabase (CREATE DATABASE practice).
In the example, ids 26, 14, 17, 20 and 23 appear on both page 0 and page 1, and other rows are never shown. Small tables often hide it; this one has 1000 orders per status.
Fix: always end the sort with a unique column, usually the id: Sort.by("status").and(Sort.by("id")).
Mistake 3: page sizes nobody limited
With no limit on size, one client can ask for size=100000 and pull a whole table through one request.
Example 3 · max-page-size and the silent fixes
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
# src/main/resources/application-web.properties (the lab's web profile)spring.data.web.pageable.max-page-size=100curl -s "http://localhost:8080/api/v1/products?size=500" | jq -c "{page, size, totalElements, totalPages}"curl -s "http://localhost:8080/api/v1/products?size=0" | jq -c "{page, size, totalElements, totalPages}"curl -s "http://localhost:8080/api/v1/products?page=-1&size=2" | jq -c "{page, size, totalElements, totalPages}"curl -s "http://localhost:8080/api/v1/products?page=abc&size=2" | jq -c "{page, size, totalElements, totalPages}"curl -i "http://localhost:8080/api/v1/products?size=2&sort=cost"$ curl -s "http://localhost:8080/api/v1/products?size=500" | jq -c "{page, size, totalElements, totalPages}"
{"page":0,"size":100,"totalElements":14,"totalPages":1}
$ curl -s "http://localhost:8080/api/v1/products?size=0" | jq -c "{page, size, totalElements, totalPages}"
{"page":0,"size":20,"totalElements":14,"totalPages":1}
$ curl -s "http://localhost:8080/api/v1/products?page=-1&size=2" | jq -c "{page, size, totalElements, totalPages}"
{"page":0,"size":2,"totalElements":14,"totalPages":7}
$ curl -s "http://localhost:8080/api/v1/products?page=abc&size=2" | jq -c "{page, size, totalElements, totalPages}"
{"page":0,"size":2,"totalElements":14,"totalPages":7}
$ curl -i "http://localhost:8080/api/v1/products?size=2&sort=cost"
HTTP/1.1 500
Content-Type: application/json
{"timestamp":"2026-10-16T08:05:54.401Z","status":500,"error":"Internal Server Error","path":"/api/v1/products"}What this code does
- With
max-page-size=100,size=500comes back as a page of 100.size=0uses the default 20;page=-1andpage=abcbecome page 0. Every call answers 200. jq -c "{page, size, totalElements, totalPages}"keeps only the page fields of the long JSON so the change is easy to see.sort=costis not a property ofProduct, so Hibernate fails and the client gets a 500 from Spring Boot's default error page (the timestamp differs on every run).
Spring Boot's default cap for a Pageable parameter is 2000 rows, which is still large, and the cap is applied silently: size=500 becomes 100, size=0 becomes 20 and page=-1 becomes 0, all with a 200. The client cannot see that its request was changed.
Fix for a public API: validate page (0 or more), size (1 to 100) and sort (an allow-list), and answer one 400 that lists every bad parameter, as ShopLite does.
Mistake 4: a joined filter that counts rows twice
A joined optional filter such as root.join("addresses") returns one row per matching address, so a customer with two Bengaluru addresses is counted twice.
Example 4 · lab/CityFilterDemo.java: join, distinct and EXISTS
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.lab;
import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Sort;import org.springframework.stereotype.Component;
import com.shoplite.customer.CustomerRepository;import com.shoplite.customer.CustomerSpecs;
@Component("specjoin")class CityFilterDemo implements LabDemo {
private final CustomerRepository customers;
CityFilterDemo(CustomerRepository customers) { this.customers = customers; }
@Override public void run() { // Asha (id 1) has TWO addresses in Bengaluru: Home and Work. Pages of 1 make the problem visible. PageRequest page0 = PageRequest.of(0, 1, Sort.by("id")); PageRequest page1 = PageRequest.of(1, 1, Sort.by("id"));
CustomerSearchDemo.print("join, page 0", customers.findAll(CustomerSpecs.hasAddressInJoin("bengaluru"), page0)); CustomerSearchDemo.print("join, page 1", customers.findAll(CustomerSpecs.hasAddressInJoin("bengaluru"), page1)); CustomerSearchDemo.print("distinct, page 0", customers.findAll(CustomerSpecs.hasAddressInDistinct("bengaluru"), page0)); CustomerSearchDemo.print("exists, page 0", customers.findAll(CustomerSpecs.hasAddressIn("bengaluru"), page0)); }}$ java -jar target/page-lab-0.1.0.jar --demo=specjoin DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 join addresses a1_0 on c1_0.customer_id=a1_0.customer_id where lower(a1_0.city)=? order by c1_0.customer_id limit ?,? DEBUG org.hibernate.SQL : select count(c1_0.customer_id) from customers c1_0 join addresses a1_0 on c1_0.customer_id=a1_0.customer_id where lower(a1_0.city)=? join, page 0 -> [Asha Rao] total=2 DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 join addresses a1_0 on c1_0.customer_id=a1_0.customer_id where lower(a1_0.city)=? order by c1_0.customer_id limit ?,? DEBUG org.hibernate.SQL : select count(c1_0.customer_id) from customers c1_0 join addresses a1_0 on c1_0.customer_id=a1_0.customer_id where lower(a1_0.city)=? join, page 1 -> [Asha Rao] total=2 DEBUG org.hibernate.SQL : select distinct c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 join addresses a1_0 on c1_0.customer_id=a1_0.customer_id where lower(a1_0.city)=? order by c1_0.customer_id limit ?,? DEBUG org.hibernate.SQL : select distinct count(distinct c1_0.customer_id) from customers c1_0 join addresses a1_0 on c1_0.customer_id=a1_0.customer_id where lower(a1_0.city)=? distinct, page 0 -> [Asha Rao] total=1 DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where exists(select 1 from addresses a1_0 where a1_0.customer_id=c1_0.customer_id and lower(a1_0.city)=?) order by c1_0.customer_id limit ?,? DEBUG org.hibernate.SQL : select count(c1_0.customer_id) from customers c1_0 where exists(select 1 from addresses a1_0 where a1_0.customer_id=c1_0.customer_id and lower(a1_0.city)=?) exists, page 0 -> [Asha Rao] total=1
What this code does
- With the plain join, the COUNT counts address rows: total 2 for one customer, and page 1 shows Asha a second time.
query.distinct(true)givesselect distinctandcount(distinct ...): total 1.- The
EXISTSversion has no join in the main query, so the plain COUNT is already right.
Asha has two Bengaluru addresses, so the COUNT says 2 and page 1 shows her again. Hibernate removes duplicate entities from one list, so a quick test without paging looks fine; the wrong total appears only with a COUNT or a small page size.
Fix: an EXISTS subquery ("has at least one address in this city"), or query.distinct(true), which also makes the COUNT distinct.
Finish up
Mark complete & continue
Next: ShopLite: paged customers and order lists