Video in progress
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:
- 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 fetchessize + 1rows to check). - Deep pages. With
OFFSET 200000the 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. - Someone may send
size=100000— cap it withspring.data.web.pageable.max-page-size. - The sort column should be indexed, otherwise every query does a filesort.
Sign up to mark studied questions and save your progress.