java 49 lines · 8 steps

Keyset pagination with Spring Data JPA

Cursor-based paging that stays fast on deep pages by seeking past the last row instead of counting offsets.

Explained by highlit
1@Repository
2public interface OrderRepository extends JpaRepository<Order, Long> {
3 
4 @Query("""
5 select o from Order o
6 where o.customerId = :customerId
7 and (o.createdAt < :lastCreatedAt
8 or (o.createdAt = :lastCreatedAt and o.id < :lastId))
9 order by o.createdAt desc, o.id desc
10 """)
11 List<Order> findNextPage(
12 @Param("customerId") Long customerId,
13 @Param("lastCreatedAt") Instant lastCreatedAt,
14 @Param("lastId") Long lastId,
15 Pageable pageable);
16 
17 @Query("""
18 select o from Order o
19 where o.customerId = :customerId
20 order by o.createdAt desc, o.id desc
21 """)
22 List<Order> findFirstPage(@Param("customerId") Long customerId, Pageable pageable);
23}
24 
25@Service
26@RequiredArgsConstructor
27class OrderPageService {
28 
29 private final OrderRepository orders;
30 
31 KeysetPage<Order> loadPage(Long customerId, String cursor, int size) {
32 Pageable limit = PageRequest.of(0, size + 1);
33 List<Order> rows = (cursor == null)
34 ? orders.findFirstPage(customerId, limit)
35 : loadAfter(customerId, Cursor.decode(cursor), limit);
36 
37 boolean hasNext = rows.size() > size;
38 List<Order> page = hasNext ? rows.subList(0, size) : rows;
39 String nextCursor = hasNext
40 ? Cursor.encode(page.get(page.size() - 1))
41 : null;
42 
43 return new KeysetPage<>(page, nextCursor);
44 }
45 
46 private List<Order> loadAfter(Long customerId, Cursor c, Pageable limit) {
47 return orders.findNextPage(customerId, c.createdAt(), c.id(), limit);
48 }
49}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Keyset pagination seeks by the last row's values rather than skipping N rows, keeping deep pages cheap.
  2. 2Ordering on a non-unique column needs a unique tie-breaker like the id to make the cursor deterministic.
  3. 3Fetching size + 1 rows tells you whether a next page exists without a separate count query.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Keyset pagination with Spring Data JPA — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code