Spring Boot / Intermediate: data, security, and framework evidence / Lesson 14
Bounded JPA pagination and projections
Retrieve a stable, authorized page of selected data and measure the cost of its query and count.
On this page
Lesson goals
- Choose bounded pagination and stable ordering.
- Project only intended fields within the ownership scope.
- Test page contents, totals and query cost.
Define a page contract
A page is more than a limit: it has a filter, ordering, size and continuation behavior. Set a maximum size and add a stable tie-breaker such as a unique identifier to the ordering. Offset-based pages can shift when concurrent writes insert or remove rows; document that behavior or choose a suitable cursor design for the use case. Never allow a page parameter to bypass tenant or visibility restrictions.
Filter before paging
The repository fragment assumes an existing Order entity and tenantId property. It filters the tenant in the database and accepts a Pageable supplied by the service. Construct that Pageable from validated, bounded client input and a server-approved sort; do not pass arbitrary field names unchecked. Test two tenants with similarly shaped records so both page contents and any count respect the intended scope.
interface OrderRepository extends JpaRepository<Order, Long> {
Page<OrderSummary> findByTenantId(Long tenantId, Pageable page);
}
The entity and tenant policy are application-specific. The caller must bound page size and constrain sorting.
Return intentional fields
A projection can select the fields required by a list rather than exposing a full managed entity to the HTTP layer. The example is an interface projection for an existing repository query. It assumes id and status properties exist. A projection does not authorize access by itself, and related properties or nested projections may still change query behavior. Measure actual SQL and returned rows on the intended provider.
interface OrderSummary {
Long getId();
String getStatus();
}
The repository may return this projection from an appropriately scoped query. It is not an authorization mechanism.
Understand count and ordering cost
A Page can provide total information, which may require an additional count query depending on execution. That query can be costly on a complex filter; measure it together with the content query. A Slice or another contract may be suitable when total counts are unnecessary, but the client must understand the changed metadata. Ensure that the chosen order is supported by appropriate indexes for the measured workload.
Verify correctness and boundaries
Populate a disposable database with multiple pages, duplicate sort values and records belonging to another tenant. Assert page contents, order, total where promised and the absence of other tenants’ records. Test zero, negative and excessive page inputs according to the application policy. Capture query count and duration with representative data; a small in-memory test cannot establish the production database plan or concurrency behavior.
Common errors and fixes
A page contains another tenant’s record
- Why it happens
- Filtering was applied after retrieving a broader page.
- How to fix it
- Apply the ownership constraint in the database query before pagination.
- Prevent it next time
- Test page contents and total with two tenants.
Records move unpredictably between pages
- Why it happens
- The sort had ties and no stable secondary key.
- How to fix it
- Add a unique tie-breaker and document concurrent-change behavior.
- Prevent it next time
- Test repeated values across page boundaries.
A small page performs a very expensive count
- Why it happens
- The cost of total metadata was not measured.
- How to fix it
- Inspect the count plan and consider a contract that does not require a total.
- Prevent it next time
- Benchmark representative filters and data volume.
2 practice exercises
1. Why can filtering a page in memory produce an incorrect total?
Show worked solution
The count and selected page may represent records outside the user’s scope. Apply the authorization filter in the query before pagination, then assert both contents and total for multiple tenants.
2. Two rows have the same creation time. How can ordering be made deterministic?
Show worked solution
Sort by creation time and a unique identifier as a tie-breaker. Test rows with equal timestamps across page boundaries, while acknowledging that concurrent inserts can still shift offset-based pages.
Key takeaways
- Filter and order at the database boundary before pagination.
- Measure count, content and resource use together.