0 Tage Serie
java / intermediate
Snippet

Speichereffiziente Datenbankabfragen mit Spring Data Window und ScrollPosition

Offset-basierte Paginierung zwingt Datenbanken zum Scannen und Verwerfen von Zeilen, was Speicherverbrauch und Abfragezeiten bei hohen Offsets erhöht. Keyset-Scrolling in Spring Data nutzt ScrollPosition und Window für inkrementelle Datenabfragen mit stabilem Speicherprofil.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public interface AuditLogRepository extends Repository<AuditLog, Long> {
Window<AuditLog> findByTenantId(String tenantId, ScrollPosition scrollPosition, Limit limit, Sort sort);
}
@Service
public class AuditLogArchiver {
private final AuditLogRepository repository;
public AuditLogArchiver(AuditLogRepository repository) {
this.repository = repository;
}
public void exportInBatches(String tenantId) {
ScrollPosition position = ScrollPosition.keyset();
Window<AuditLog> currentWindow;
do {
currentWindow = repository.findByTenantId(
tenantId, position, Limit.of(500), Sort.by("id").ascending()
);
processBatch(currentWindow.getContent());
position = currentWindow.positionAt(currentWindow.size() - 1);
} while (!currentWindow.isEmpty() && currentWindow.hasNext());
}
}
spring
Erklärung
1
Window<AuditLog> findByTenantId(String tenantId, ScrollPosition scrollPosition, Limit limit, Sort sort);
Deklariert eine Repository-Methode, die ein Window-Segment basierend auf einer ScrollPosition statt eines Integer-Offsets zurückgibt.
2
ScrollPosition position = ScrollPosition.keyset();
Initialisiert einen Keyset-basierten Cursor, der Ergebnisse anhand von Primärschlüssel-Indizes durchläuft.
3
position = currentWindow.positionAt(currentWindow.size() - 1);
Extrahiert die Cursor-Position des letzten Elements im aktuellen Batch zur Vorbereitung der nächsten Abfrage-Iteration.