13 · Persistence / LESSON 60 OF 102
Repositories and pagination
Fetch bounded data in a deterministic order.
Before this lesson: JPA entities and PostgreSQL
Understand the topic
Spring Data generates repository implementations. JpaRepository provides save, findById, and delete methods. Derived queries express simple predicates; use explicit queries for complex cases.
Pagination bounds response size and memory. Page indices start at zero. Sort by a unique tie-breaker such as id to avoid unstable page boundaries. Lazy associations can cause N+1 queries; inspect generated SQL and query counts.
EXAMPLE · JAVA
src/main/java/com/example/tasks/TaskRepository.java
package com.example.tasks;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TaskRepository extends JpaRepository<Task, Long> {
Page<Task> findByDone(boolean done, Pageable pageable);
}
// Example inside a service method:
// repository.findByDone(false, PageRequest.of(0, 20, Sort.by("id")));What to expect
The repository is injectable. The example query retrieves up to 20 incomplete tasks with page metadata.
YOUR TURN
Put it into practice
- 01Add a findById service method.
- 02Clamp requested page sizes to a documented maximum.
- 03Insert 25 rows and verify stable, non-overlapping pages.
Pass a quiz or complete a lab to check today’s streak. Each lesson counts once per day, including when you review it later.
UNDER THE HOOD
Build the mental model
A repository is a query boundary. Its convenience methods do not remove the need to understand SQL cost and access scope.
- 01Page can require a count query in addition to fetching rows. Slice is useful when the client only needs to know whether more data exists.
- 02Offset pagination is simple but can become expensive at large offsets. Keyset pagination uses a stable ordered key and a cursor for suitable workloads.
- 03Owner restrictions belong in queries as well as service checks. Never fetch all rows and filter unauthorized ones in memory.
A mistake worth avoiding
Sorting by a non-unique field alone can produce unstable pages.
DEBUGGING ROOM
Something broke. Where do you look?
A list endpoint makes one query for tasks and one extra query per owner.
Before revealing the diagnosis, write down your first investigation step.
CHECK YOUR UNDERSTANDING
What commonly causes N+1 queries?
BUILD IT YOURSELF
Build bounded owner-scoped queries
- 1.Return only the current owner’s tasks.
- 2.Clamp page size and define stable sorting.
- 3.Measure query counts on a representative dataset.
Acceptance checklist
Lab completion is your self-report. Knowledge checks do not certify project quality.
RETRIEVE IT FROM MEMORY
When would Slice be cheaper than Page?
Revisit this lesson in three days after a successful check or lab.
Ready for the next step?
Explain Optional, derived queries, sorting, and pagination.
Reading is separate from passing a knowledge check or completing a lab.