滾動
滾動是一種更精細的方法,用於迭代更大的結果集塊。滾動包括穩定排序、滾動型別(基於偏移量或基於 Keyset 的滾動)和結果限制。您可以透過使用屬性名稱來定義簡單的排序表示式,並透過查詢派生使用 Top
或 First
關鍵字來定義靜態結果限制。您可以連線表示式以將多個條件收集到一個表示式中。
滾動查詢返回一個 Window<T>
,它允許獲取元素的滾動位置以獲取下一個 Window<T>
,直到您的應用程式消費完整個查詢結果。類似於透過獲取下一批結果來消費 Java 的 Iterator<List<…>>
,查詢結果滾動讓您透過 Window.positionAt(…)
訪問 ScrollPosition
。
Window<User> users = repository.findFirst10ByLastnameOrderByFirstname("Doe", ScrollPosition.offset());
do {
for (User u : users) {
// consume the user
}
// obtain the next Scroll
users = repository.findFirst10ByLastnameOrderByFirstname("Doe", users.positionAt(users.size() - 1));
} while (!users.isEmpty() && users.hasNext());
|
上述示例展示了靜態排序和限制。您也可以定義接受 |
WindowIterator
提供了一個工具,透過消除檢查是否存在下一個 Window
並應用 ScrollPosition
的需要,從而簡化了在 Window
之間的滾動。
WindowIterator<User> users = WindowIterator.of(position -> repository.findFirst10ByLastnameOrderByFirstname("Doe", position))
.startingAt(ScrollPosition.offset());
while (users.hasNext()) {
User u = users.next();
// consume the user
}
使用偏移量進行滾動
基於偏移量的滾動與分頁類似,使用一個偏移量計數器來跳過一定數量的結果,並讓資料來源僅返回從給定偏移量開始的結果。這種簡單的機制避免了將大量結果傳送到客戶端應用程式。然而,大多數資料庫在您的伺服器返回結果之前,需要具體化(materialize)完整的查詢結果。
OffsetScrollPosition
interface UserRepository extends Repository<User, Long> {
Window<User> findFirst10ByLastnameOrderByFirstname(String lastname, OffsetScrollPosition position);
}
WindowIterator<User> users = WindowIterator.of(position -> repository.findFirst10ByLastnameOrderByFirstname("Doe", position))
.startingAt(OffsetScrollPosition.initial()); (1)
1 | 從無偏移量開始,以包含位置為 0 的元素。 |
|
使用 Keyset-Filtering 進行滾動
基於偏移量的滾動要求大多數資料庫在您的伺服器返回結果之前具體化整個結果。因此,儘管客戶端只看到請求結果的一部分,您的伺服器需要構建完整結果,這會導致額外的負載。
Keyset-Filtering 透過利用資料庫的內建能力來檢索結果子集,旨在減少單個查詢的計算和 I/O 要求。這種方法維護一組鍵,透過將鍵傳遞到查詢中來恢復滾動,有效地修改了您的過濾條件。
Keyset-Filtering 的核心思想是使用穩定的排序順序開始檢索結果。一旦您想滾動到下一個塊,您將獲得一個 ScrollPosition
,用於重建在排序結果中的位置。ScrollPosition
捕獲當前 Window
中最後一個實體的 keyset。為了執行查詢,重構會重寫條件子句,使其包含所有排序欄位和主鍵,以便資料庫可以利用潛在的索引來執行查詢。資料庫只需要從給定的 keyset 位置構建一個更小的結果,而無需完全具體化大型結果,然後跳過結果直到達到特定偏移量。
Keyset-Filtering 要求 keyset 屬性(用於排序的屬性)不可為空(non-nullable)。此限制適用於由於儲存特定(store specific)的比較運算子對 null 值的處理,以及需要針對索引源執行查詢。對可空屬性使用 Keyset-Filtering 會導致意外結果。 |
KeysetScrollPosition
interface UserRepository extends Repository<User, Long> {
Window<User> findFirst10ByLastnameOrderByFirstname(String lastname, KeysetScrollPosition position);
}
WindowIterator<User> users = WindowIterator.of(position -> repository.findFirst10ByLastnameOrderByFirstname("Doe", position))
.startingAt(ScrollPosition.keyset()); (1)
1 | 從最開始處啟動,不應用額外的過濾。 |
當您的資料庫包含與排序欄位匹配的索引時,Keyset-Filtering 的效果最好,因此靜態排序非常有效。應用 Keyset-Filtering 的滾動查詢要求查詢返回排序順序中使用的屬性,並且這些屬性必須對映到返回的實體中。
您可以使用介面和 DTO 投影,但請務必包含所有您排序所用的屬性,以避免 keyset 提取失敗。
在指定您的 Sort
順序時,只需包含與您的查詢相關的排序屬性即可;如果您不需要,則無需確保查詢結果的唯一性。keyset 查詢機制會透過包含主鍵(或複合主鍵的任何剩餘部分)來修改您的排序順序,以確保每個查詢結果都是唯一的。