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

java
@Component
@Converter
public class EncryptedStringConverter implements AttributeConverter<String, String> {
 

Transparent column encryption in Spring & JPA

encryption aes-gcm jpa-converter
Advanced 10 steps
java
package com.acme.billing.config;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

Feature-flagged beans with Spring @ConditionalOnProperty

feature-flags conditional-beans strategy-pattern
Intermediate 5 steps
java
public static Map<String, String> parseCookieHeader(String header) {
    Map<String, String> cookies = new LinkedHashMap<>();
    if (header == null || header.isBlank()) {
        return cookies;

Parsing an HTTP Cookie header in Java

string-parsing http url-decoding
Intermediate 6 steps
java
public class TimedSocketReader {
 
    private static final int READ_TIMEOUT_MS = 5_000;
    private static final int CONNECT_TIMEOUT_MS = 3_000;

Reading a socket with connect and read timeouts

sockets timeouts io
Intermediate 8 steps
java
public final class EncodingDetector {
 
    public enum Encoding {
        UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN

Detecting text encoding from raw bytes in Java

byte-manipulation encoding-detection bitwise-operations
Intermediate 8 steps
java
public final class ImportOrganizer {
 
    private static final Pattern IMPORT_LINE =
            Pattern.compile("^import\\s+(static\\s+)?([\\w.]+(?:\\.\\*)?)\\s*;\\s*$");

Sorting Java imports with a regex pass

regex sorting text-processing
Intermediate 8 steps

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