Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 33

    Pagination & Sorting

    Unbounded Orders lists become production incidents.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Unbounded Orders lists become production incidents. Spring Data's Pageable and Page<T> give offset pagination and sorting with almost no boilerplate — but you must cap page size and choose stable sort keys.

    Controllers accept Pageable (or explicit page/size/sort params). Repositories take Pageable on finder methods. Prefer @PageableDefault for sensible defaults (size=20, sort by createdAt DESC). Hard-cap maximum size (for example 100) so clients cannot request a million rows.

    Offset pagination slows on deep pages. For very large ledgers, plan keyset/cursor pagination (where id < :cursor). Always include a unique tiebreaker in sort order to avoid duplicate/missing rows across pages.

    Map Page<Order> to Page<OrderView> (or a custom page DTO) — never return entities.

    Purpose of this lesson

    Page and sort Orders lists with Spring Data Pageable, safe defaults, size caps, and stable ordering.

    Understanding the topic

    Pagination is an API contract and a database kindness.

    • Pageable: page index, size, sort.
    • Page<T>: content + total elements/pages metadata.
    • defaults: @PageableDefault for empty query strings.
    • caps: reject oversized size to protect Postgres.
    • cursors: better than deep offsets at scale.

    Step-by-step explanation

    1. Add Page<Order> findByStatus(OrderStatus, Pageable) to the repository.
    2. Expose GET /api/orders with @PageableDefault.
    3. Map to OrderView; enforce a max size in a resolver or manual check.
    4. Verify ?page=0&size=20&sort=createdAt,desc against sample data.

    Informative example

    Paged Orders list.

    java
    // Repository
    Page<Order> findByStatus(OrderStatus status, Pageable pageable);
    // Controller
    @GetMapping
    Page<OrderView> list(
    @RequestParam(defaultValue = "PENDING") OrderStatus status,
    @PageableDefault(size = 20, sort = "createdAt",
    direction = Sort.Direction.DESC) Pageable pageable) {
    if (pageable.getPageSize() > 100) {
    throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "size max 100");
    }
    return orderService.list(status, pageable);
    }
    // Service
    @Transactional(readOnly = true)
    public Page<OrderView> list(OrderStatus status, Pageable pageable) {
    return orders.findByStatus(status, pageable).map(OrderView::from);
    }
    // GET /api/orders?status=PAID&page=2&size=50&sort=totalCents,desc

    Output

    {
      "content": [{"id": 90, "status": "PAID", "amountCents": 4999}],
      "totalElements": 134,
      "totalPages": 3,
      "number": 2,
      "size": 50
    }

    Real-world use

    Ops browses TechLearningPRO paid orders during a sale. Without size caps, a mistaken size=100000 could exhaust memory and the pool. Defaults plus a hard cap keep the dashboard responsive.

    Security implications

    Pagination parameters are attacker-controlled.

    • Cap size to prevent resource exhaustion.
    • Do not allow sorting on arbitrary entity graphs without a whitelist.
    • Still filter by tenant/user — paging is not authorization.

    Best practices

    • Default sort includes a unique tiebreaker (createdAt, id).
    • Prefer Slice when total count is unnecessary.
    • Plan cursor pagination for infinite-scroll mobile feeds.

    Common mistakes

    • Sorting only by a non-unique column (duplicate rows across pages).
    • Returning List from finders that should be paged.
    • Counting total elements on huge tables for every request without caching strategy — know the cost of Page vs Slice.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat does Pageable encapsulate?+

    Answer

    Page index, page size, and sort criteria passed into Spring Data repository methods.
    2BeginnerQuestionWhy cap page size?+

    Answer

    To prevent clients from requesting huge result sets that overload the database and JVM.
    3AdvancedQuestionWhen prefer keyset pagination over offset?+

    Answer

    When deep pages make OFFSET expensive; keyset uses a seek predicate on the last seen key for stable performance.

    Hands-on exercise

    Lab. Seed 50 orders. Call page 0 size 20 and page 1 size 20; confirm no overlap with a unique sort. Then request size 500 and assert your cap rejects it.

    Summary

    Pagination keeps Orders lists honest under growth. Next: wrap multi-step writes in transactions.

    Ready to mark this lesson complete?Track your journey across the entire course.