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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Keyset pagination seeks by the last row's values rather than skipping N rows, keeping deep pages cheap.
- 2Ordering on a non-unique column needs a unique tie-breaker like the id to make the cursor deterministic.
- 3Fetching size + 1 rows tells you whether a next page exists without a separate count query.
Related explainers
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
java
public record FixedWidthField(String name, int start, int end) { public String extract(String line) { int from = Math.min(start, line.length());
Parsing fixed-width text in Java
records
parsing
streams
Intermediate
7 steps
java
@RestController @RequestMapping("/api/quotes") public class QuoteStreamController {
Streaming market quotes with Spring WebFlux
reactive-streams
backpressure
server-sent-events
Advanced
9 steps
java
@Controller public class BookController { private final BookService bookService;
Solving GraphQL N+1 with batch mapping in Spring
graphql
n+1-problem
batching
Intermediate
8 steps
java
@Component required to import public class OutboxEventPublisher {
The transactional outbox pattern in Spring
transactional-outbox
event-driven
reliability
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/keyset-pagination-with-spring-data-jpa-explained-java-7d8a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.