Video in progress

Middle 🌱 Spring

How do Pageable and Page work in Spring Data, and what should you watch for on a large table?

Pageable is the page number, size and sorting. Page returns the total count on top of the results, and that takes a separate COUNT query. If you don't need the total, use Slice.

📖 Answer

public interface OrderRepository extends JpaRepository<Order, Long> {
    Page<Order> findByCustomerId(long customerId, Pageable pageable);
    Slice<Order> findByStatus(Status status, Pageable pageable);
}

@GetMapping("/api/orders")
public Page<OrderDto> list(@RequestParam long customerId,
                           @PageableDefault(size = 20, sort = "createdAt", direction = DESC) Pageable p) {
    return orders.findByCustomerId(customerId, p).map(OrderDto::of);
}

The client sends ?page=2&size=20&sort=createdAt,desc.

What hurts on a large table:

  1. COUNT is expensive. On a table with a million rows count(*) is recomputed for every page. If "is there a next page?" is enough — Slice (it fetches size + 1 rows to check).
  2. Deep pages. With OFFSET 200000 the database still walks through 200 thousand rows. If you need that kind of paging, use keyset (seek) pagination: where id < :lastId order by id desc limit 20.
  3. Someone may send size=100000 — cap it with spring.data.web.pageable.max-page-size.
  4. The sort column should be indexed, otherwise every query does a filesort.