滾動
滾動是一種更細粒度的方法,用於迭代較大的結果集塊。滾動包括一個穩定的排序、一個滾動型別(基於偏移量的滾動或基於 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
}
使用偏移量滾動
偏移量滾動類似於分頁,使用一個偏移量計數器來跳過一定數量的結果,並讓資料來源只返回從給定偏移量開始的結果。這種簡單的機制避免了向客戶端應用傳送大量結果。然而,大多數資料庫要求在您的伺服器返回結果之前將整個查詢結果具體化。
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 屬性(用於排序的屬性)非空。此限制的適用是由於儲存特定資料庫處理比較運算子中的 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 查詢機制透過包含主鍵(或複合主鍵的任何剩餘部分)來修正您的排序順序,以確保每個查詢結果唯一。