Pageable, Page and Slice
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite has 14 products today and will have 2 lakh. A screen shows 20 at a time, so the app must ask for one small piece of the list, not the whole table, on every request.
PageRequest.of(page, size): pages start at 0
Pageable is the Spring Data object that says which page you want and how many rows a page holds, built with PageRequest.of(page, size). Pages start at 0. As the last parameter of a repository method, it makes Spring Data add LIMIT and OFFSET.
A page request has two numbers: the page, counted from 0, and the size. PageRequest.of(2, 5) is the third page of five rows.
Example 1 · src/main/java/com/shoplite/product/ProductRepository.java
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.product;
import java.math.BigDecimal;import java.util.List;
import org.springframework.data.domain.Page;import org.springframework.data.domain.Pageable;import org.springframework.data.domain.Slice;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Query;import org.springframework.data.repository.query.Param;
public interface ProductRepository extends JpaRepository<Product, Integer> {
// Page: one page of rows plus the totals (needs a second, COUNT query) Page<Product> findByActiveTrue(Pageable pageable);
// Slice: one page of rows and "is there more?" (no COUNT query) Slice<Product> findByPriceLessThan(BigDecimal price, Pageable pageable);
List<Product> findByStockGreaterThan(int stock, Pageable pageable);
@Query(value = "select p.* from products p join categories c on c.category_id = p.category_id " + "where c.name = :category", nativeQuery = true) Page<Product> findInCategoryNative(@Param("category") String category, Pageable pageable);
// The same query with its own countQuery @Query(value = "select p.* from products p join categories c on c.category_id = p.category_id " + "where c.name = :category", countQuery = "select count(*) from products p join categories c on c.category_id = p.category_id " + "where c.name = :category", nativeQuery = true) Page<Product> findInCategory(@Param("category") String category, Pageable pageable);
@Query(value = "select p from Product p join fetch p.category where p.active = true", countQuery = "select count(p) from Product p where p.active = true") Page<Product> findActiveWithCategory(Pageable pageable);
}(no output: Examples 2 to 5 call these methods)
What this code does
- Every paged method takes a
Pageableas its last parameter. Spring Data addsLIMIT/OFFSETand theORDER BYfrom thePageableitself. - The return type decides the extra work:
Pageadds a COUNT,Sliceasks for one extra row,Listdoes neither. findInCategorygives its owncountQuery;findInCategoryNativedoes not, and Example 5 shows what happens.
Example 2 · lab/FirstPagesDemo.java: the first page and the third page
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.Pageable;import org.springframework.data.domain.Sort;import org.springframework.stereotype.Component;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("page")class FirstPagesDemo implements LabDemo {
private final ProductRepository products;
FirstPagesDemo(ProductRepository products) { this.products = products; }
@Override public void run() { Pageable first = PageRequest.of(0, 5, Sort.by("id")); // page 0 = the first page print(products.findByActiveTrue(first));
Pageable third = PageRequest.of(2, 5, Sort.by("id")); // page 2 = the third page print(products.findByActiveTrue(third)); }
private static void print(Page<Product> page) { System.out.println("Page " + page.getNumber() + " of " + page.getTotalPages() + " | size " + page.getSize() + " | rows here " + page.getNumberOfElements() + " | total " + page.getTotalElements()); page.getContent().forEach(p -> System.out.println(" " + p.getId() + " " + p.getName())); System.out.println(" first=" + page.isFirst() + " last=" + page.isLast() + " hasNext=" + page.hasNext()); }}$ java -jar target/page-lab-0.1.0.jar --demo=page DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.is_active=true order by p1_0.product_id limit ? DEBUG org.hibernate.SQL : select count(p1_0.product_id) from products p1_0 where p1_0.is_active=true Page 0 of 3 | size 5 | rows here 5 | total 14 1 Redmi Note 13 5G 2 Samsung Galaxy M35 3 iPhone 15 128GB 4 Lenovo IdeaPad Slim 3 5 HP Victus 15 Gaming first=true last=false hasNext=true DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.is_active=true order by p1_0.product_id limit ?,? Page 2 of 3 | size 5 | rows here 4 | total 14 11 Atomic Habits 12 Cotton Kurta 13 Running Shoes 14 Prestige Pressure Cooker 3L first=false last=true hasNext=false
What this code does
- Page 0 uses
limit ?(skip nothing, take 5); page 2 useslimit ?,?(skip 10, take 5) and shows rows 11 to 14. - Page 0 is full, so Spring Data sends a COUNT and learns there are 14 active products: 3 pages. Page 2 has only 4 rows, so the total is 10 + 4 = 14 and no COUNT is sent.
Sort.by("id")gives the pages a fixed order. Without an order, the database may return rows in any order (the next lesson).
The offset is the number of rows to skip: page × size, so page 2 of size 5 skips 10 rows and shows rows 11 to 15. MySQL writes it as LIMIT 10, 5; the log shows limit ?,? because the values are sent as parameters.
Without pages, findAll() on a table with 2 lakh products loads all 2 lakh rows into memory for one screen of 20. That is slow for the database, the network and the Java heap, and it gets worse every day the table grows.
java -jar target/page-lab-0.1.0.jar --demo=page runs the one named page. logging.level.org.hibernate.SQL=DEBUG prints every SQL statement.Page<T>: the rows, the totals and the extra COUNT query
Page<T> is one page of rows plus what a page bar needs: the total rows, the total pages and whether a next page exists. To learn the totals, Spring Data sends a second query, SELECT COUNT(...), with the same WHERE.
A Page answers two questions: which rows are on this page, and how many pages are there. The SQL log shows both queries.
Example 3 · lab/CountRuleDemo.java: when the COUNT runs
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 com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("pagecount")class CountRuleDemo implements LabDemo {
private final ProductRepository products;
CountRuleDemo(ProductRepository products) { this.products = products; }
@Override public void run() { // All 14 active products fit on one page of 20 Page<Product> all = products.findByActiveTrue(PageRequest.of(0, 20, Sort.by("id"))); System.out.println("size 20, page 0: " + all.getNumberOfElements() + " rows, total " + all.getTotalElements() + ", pages " + all.getTotalPages());
// Page 5 of size 5 starts at row 25: past the end Page<Product> past = products.findByActiveTrue(PageRequest.of(5, 5, Sort.by("id"))); System.out.println("size 5, page 5: " + past.getNumberOfElements() + " rows, total " + past.getTotalElements() + ", hasContent " + past.hasContent()); }}$ java -jar target/page-lab-0.1.0.jar --demo=pagecount DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.is_active=true order by p1_0.product_id limit ? size 20, page 0: 14 rows, total 14, pages 1 DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.is_active=true order by p1_0.product_id limit ?,? DEBUG org.hibernate.SQL : select count(p1_0.product_id) from products p1_0 where p1_0.is_active=true size 5, page 5: 0 rows, total 14, hasContent false
What this code does
- A page of 20 holds all 14 products, so the first page is not full: one SELECT, no COUNT, total 14.
- Page 5 starts at row 25. The SELECT returns nothing, so Spring Data must count to report the real total of 14.
hasContent()is false: the client shows "No more products", not an error.
Useful methods are getTotalElements(), getTotalPages(), getNumber(), isFirst(), isLast() and hasNext(). Spring Data skips the COUNT when it can work the total out: a first page that is not full (14 rows for a page of 20) means the total is 14, and a later page that is not full means offset + rows on the page. Only a full page, or a page past the end, needs the COUNT.
A page past the end is not an error. You get an empty content and the real totals, so the client can show "No more products" and jump back to the last page.
Predict the output
Which rows, and how many queries?
Pick what Spring Data does.
Round 1 of 2
ShopLite asks for the third page of five products.
Slice<T> and List: no COUNT query
Slice<T> is one page of rows that knows only whether a next page exists (hasNext()), not how many pages there are. Spring Data asks for one row more than the page size, so no COUNT query runs.
A slice answers "is there more?" and nothing else. That is all a "Load more" button or infinite scroll needs.
Example 4 · lab/LoadMoreDemo.java: a Slice for "Load more", and a List
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.lab;
import java.math.BigDecimal;import java.util.List;
import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Slice;import org.springframework.data.domain.Sort;import org.springframework.stereotype.Component;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("slice")class LoadMoreDemo implements LabDemo {
private final ProductRepository products;
LoadMoreDemo(ProductRepository products) { this.products = products; }
@Override public void run() { // A "Load more" list: gifts under Rs 2000, cheapest first, 4 at a time BigDecimal budget = new BigDecimal("2000"); Slice<Product> slice = products.findByPriceLessThan(budget, PageRequest.of(0, 4, Sort.by("price"))); while (true) { System.out.println("Slice " + slice.getNumber() + ": " + slice.getContent().stream().map(Product::getName).toList() + " hasNext=" + slice.hasNext()); if (!slice.hasNext()) { break; } slice = products.findByPriceLessThan(budget, slice.nextPageable()); }
// A List with a Pageable: rows 4 to 6 of the in-stock products, nothing else List<Product> list = products.findByStockGreaterThan(0, PageRequest.of(1, 3, Sort.by("id"))); System.out.println("List: " + list.stream().map(Product::getName).toList()); }}$ java -jar target/page-lab-0.1.0.jar --demo=slice DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.price<? order by p1_0.price limit ? Slice 0: [USB-C Cable 1m, Atomic Habits, Clean Code, The Pragmatic Programmer] hasNext=true DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.price<? order by p1_0.price limit ?,? Slice 1: [Logitech M331 Silent Mouse, Cotton Kurta, boAt Airdopes 141, Prestige Pressure Cooker 3L] hasNext=false DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.stock>? order by p1_0.product_id limit ?,? List: [Lenovo IdeaPad Slim 3, HP Victus 15 Gaming, boAt Airdopes 141]
What this code does
- No COUNT appears in the log. For a slice of 4, Spring Data asks for 5 rows; the fifth row only tells it that
hasNext()is true. slice.nextPageable()moves to page 1. That slice has 4 rows and no fifth, sohasNext()is false and the loop stops.- The
Listmethod sends one SELECT withlimit ?,?and returns only rows 4 to 6 of the in-stock products.
A paged method can return three things:
Page<T>: rows + totals; 1 SELECT + usually 1 COUNT. For page bars ("1 2 3 ... 7").Slice<T>: rows +hasNext(); 1 SELECT with one extra row. For "Load more".List<T>with aPageable: rows only; 1 SELECT. For "top N" lists.
slice.nextPageable() gives the Pageable for the next request. A List<T> has no totals and no hasNext(), so use it when the caller just needs "the top 10" or already knows how many rows exist.
A custom countQuery for @Query pages
countQuery is the COUNT statement you write yourself for a paged @Query: @Query(value = "...", countQuery = "select count(*) ..."). It keeps the same WHERE and the joins that change the row count, and drops everything else.
Spring Data writes the COUNT for you by rewriting your query. For native SQL that rewrite can be wrong; Example 5 shows the failure.
Example 5 · lab/CountQueryDemo.java: a derived COUNT that breaks, and the fix
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.stereotype.Component;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("countquery")class CountQueryDemo implements LabDemo {
private final ProductRepository products;
CountQueryDemo(ProductRepository products) { this.products = products; }
@Override public void run() { try { Page<Product> page = products.findInCategoryNative("Accessories", PageRequest.of(0, 2)); System.out.println("Derived count: total " + page.getTotalElements()); } catch (RuntimeException e) { System.out.println("Derived count failed: " + e.getClass().getSimpleName()); }
Page<Product> page = products.findInCategory("Accessories", PageRequest.of(0, 2)); System.out.println("Own countQuery: " + page.getContent().stream().map(Product::getName).toList() + ", total " + page.getTotalElements()); }}$ java -jar target/page-lab-0.1.0.jar --demo=countquery DEBUG org.hibernate.SQL : select p.* from products p join categories c on c.category_id = p.category_id where c.name = ? limit ? DEBUG org.hibernate.SQL : select count(p.*) from products p join categories c on c.category_id = p.category_id where c.name = ? WARN org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 1064, SQLState: 42000 WARN org.hibernate.orm.jdbc.error : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*) from products p join categories c on c.category_id = p.category_id where c.na' at line 1 Derived count failed: InvalidDataAccessResourceUsageException DEBUG org.hibernate.SQL : select p.* from products p join categories c on c.category_id = p.category_id where c.name = ? limit ? DEBUG org.hibernate.SQL : select count(*) from products p join categories c on c.category_id = p.category_id where c.name = ? Own countQuery: [boAt Airdopes 141, Mi Power Bank 20000mAh], total 4
What this code does
- Accessories has 4 products, so the first page of 2 is full and a COUNT is needed. The derived
count(p.*)is a MySQL syntax error (code 1064). - With
countQuery = "select count(*) ..."the same page works and reports the real total of 4. - This bug hides in tests with little data: while the first page is not full, no COUNT runs and everything looks fine.
For derived methods and simple JPQL the rewrite is fine. For native SQL, GROUP BY and other complex queries it can be wrong or slow. The native query here gets select count(p.*) ..., which is not valid MySQL, so the first page works only while it is not full, and the request fails with a syntax error the moment a COUNT is needed.
The fix is one attribute: write the COUNT yourself, and drop ORDER BY, fetch joins and extra columns from it.
Fetch join + paging: "applying in memory"
HHH90003004 is the Hibernate 6 warning "firstResult/maxResults specified with collection fetch; applying in memory". It means every row was loaded and the page was cut in Java memory, because a LIMIT cannot be applied to a collection fetch join.
A collection fetch join (join fetch o.items) with a Pageable is a trap. The log below is what Hibernate 6 writes for it.
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 6 · 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
OrderRepository.findAllWithItemsisselect o from Order o join fetch o.itemswith acountQuery, called with a page of 3.- Hibernate 7.4 puts the
limit ?,?inside a subquery overorders, then joinsorder_items: each order keeps all its items and no warning is logged. - On Spring Boot 3 (Hibernate 6) the same call loads every order and logs HHH90003004, as the section shows.
The SQL returns one row per item, not per order, so LIMIT 3 would cut an order's items in half. Hibernate 6 (Spring Boot 3) therefore pages in Java memory: on a table with 50,000 orders, one request for 20 orders reads all 50,000.
Hibernate 7.4 (Spring Boot 4.1) on MySQL behaves better: Example 6 shows it pages the orders in a subquery first, with no warning. The rule holds for both versions: do not page a collection fetch join. Page the parent rows (or their ids), then load the children; the Performance Traps module shows the full fix.
Next step
Check your understanding
11 quick questions