範例查詢

簡介

本章節簡介範例查詢,並說明如何使用它。

範例查詢 (QBE) 是一種使用者友善的查詢技術,具有簡單的介面。它允許動態建立查詢,且不需要您撰寫包含欄位名稱的查詢。實際上,範例查詢完全不需要您使用特定儲存區的查詢語言來撰寫查詢。

本章節說明範例查詢的核心概念。這些資訊來自 Spring Data Commons 模組。根據您的資料庫,字串比對支援可能會受到限制。

用法

範例查詢 API 由四個部分組成

  • 探針 (Probe):具有已填入欄位的領域物件的實際範例。

  • ExampleMatcherExampleMatcher 載有關於如何比對特定欄位的詳細資訊。它可以跨多個範例重複使用。

  • ExampleExample 由探針和 ExampleMatcher 組成。它用於建立查詢。

  • FetchableFluentQueryFetchableFluentQuery 提供流暢的 API,可進一步自訂從 Example 衍生的查詢。使用流暢的 API 可讓您為查詢指定排序、投影和結果處理。

範例查詢非常適合多種使用情境

  • 使用一組靜態或動態約束查詢您的資料儲存區。

  • 頻繁地重構領域物件,而無需擔心破壞現有的查詢。

  • 獨立於底層資料儲存區 API 工作。

範例查詢也有一些限制

  • 不支援巢狀或群組屬性約束,例如 firstname = ?0 or (firstname = ?1 and lastname = ?2)

  • 儲存區特定的字串比對支援。根據您的資料庫,字串比對可以支援字串的 starts/contains/ends/regex。

  • 其他屬性類型的精確比對。

在開始使用範例查詢之前,您需要有一個領域物件。若要開始,請為您的 Repository 建立介面,如下列範例所示

範例 Person 物件
public class Person {

  @Id
  private String id;
  private String firstname;
  private String lastname;
  private Address address;

  // … getters and setters omitted
}

前面的範例顯示了一個簡單的領域物件。您可以使用它來建立一個 Example。預設情況下,具有 null 值的欄位會被忽略,而字串則使用儲存區特定的預設值進行比對。

將屬性包含到範例查詢條件中是基於可空性。除非 ExampleMatcher 忽略屬性路徑,否則使用原始型別 (int, double, …) 的屬性始終包含在內。

範例可以使用 of 工廠方法或使用 ExampleMatcher 來建立。Example 是不可變的。以下列表顯示了一個簡單的範例

範例 1. 簡單範例
Person person = new Person();                         (1)
person.setFirstname("Dave");                          (2)

Example<Person> example = Example.of(person);         (3)
1 建立領域物件的新實例。
2 設定要查詢的屬性。
3 建立 Example。

您可以使用 Repository 來執行範例查詢。若要執行此操作,請讓您的 Repository 介面擴展 QueryByExampleExecutor<T>。以下列表顯示了 QueryByExampleExecutor 介面的摘錄

QueryByExampleExecutor
public interface QueryByExampleExecutor<T> {

  <S extends T> S findOne(Example<S> example);

  <S extends T> Iterable<S> findAll(Example<S> example);

  // … more functionality omitted.
}

Example Matchers

範例不限於預設設定。您可以使用 ExampleMatcher 指定自己的字串比對、Null 處理和屬性特定設定的預設值,如下列範例所示

範例 2. 具有自訂比對的 Example matcher
Person person = new Person();                          (1)
person.setFirstname("Dave");                           (2)

ExampleMatcher matcher = ExampleMatcher.matching()     (3)
  .withIgnorePaths("lastname")                         (4)
  .withIncludeNullValues()                             (5)
  .withStringMatcher(StringMatcher.ENDING);            (6)

Example<Person> example = Example.of(person, matcher); (7)
1 建立領域物件的新實例。
2 設定屬性。
3 建立一個 ExampleMatcher 以期望所有值都比對。即使沒有進一步的設定,它在此階段也是可用的。
4 建構一個新的 ExampleMatcher 以忽略 lastname 屬性路徑。
5 建構一個新的 ExampleMatcher 以忽略 lastname 屬性路徑並包含 null 值。
6 建構一個新的 ExampleMatcher 以忽略 lastname 屬性路徑、包含 null 值,並執行後綴字串比對。
7 基於領域物件和已設定的 ExampleMatcher 建立一個新的 Example。

預設情況下,ExampleMatcher 期望探針上設定的所有值都比對。如果您想要取得符合任何隱含定義的述詞的結果,請使用 ExampleMatcher.matchingAny()

您可以為個別屬性 (例如 "firstname" 和 "lastname",或對於巢狀屬性,"address.city") 指定行為。您可以使用比對選項和區分大小寫來調整它,如下列範例所示

設定 matcher 選項
ExampleMatcher matcher = ExampleMatcher.matching()
  .withMatcher("firstname", endsWith())
  .withMatcher("lastname", startsWith().ignoreCase());
}

設定 matcher 選項的另一種方法是使用 lambda (在 Java 8 中引入)。此方法建立一個回呼,要求實作者修改 matcher。您不需要傳回 matcher,因為設定選項保留在 matcher 實例中。以下範例顯示了一個使用 lambda 的 matcher

使用 lambda 設定 matcher 選項
ExampleMatcher matcher = ExampleMatcher.matching()
  .withMatcher("firstname", match -> match.endsWith())
  .withMatcher("firstname", match -> match.startsWith());
}

由 Example 建立的查詢使用設定的合併視圖。預設比對設定可以在 ExampleMatcher 層級設定,而個別設定可以應用於特定屬性路徑。除非明確定義,否則在 ExampleMatcher 上設定的設定會由屬性路徑設定繼承。屬性修補程式上的設定優先順序高於預設設定。下表描述了各種 ExampleMatcher 設定的範圍

表 1. ExampleMatcher 設定的範圍
設定 範圍

Null 處理

ExampleMatcher

字串比對

ExampleMatcher 和屬性路徑

忽略屬性

屬性路徑

區分大小寫

ExampleMatcher 和屬性路徑

值轉換

屬性路徑

Fluent API

QueryByExampleExecutor 提供了另一個方法,我們到目前為止尚未提及:<S extends T, R> R findBy(Example<S> example, Function<FluentQuery.FetchableFluentQuery<S>, R> queryFunction)。與其他方法一樣,它執行從 Example 衍生的查詢。但是,使用第二個引數,您可以控制執行的各個方面,否則您無法動態控制這些方面。您可以透過調用第二個引數中 FetchableFluentQuery 的各種方法來執行此操作。sortBy 可讓您指定結果的排序方式。as 可讓您指定要將結果轉換成的類型。project 限制了查詢的屬性。firstfirstValueoneoneValueallpagestreamcountexists 定義了您獲得的結果類型,以及當可用結果數量超過預期數量時查詢的行為方式。

使用 Fluent API 取得可能多個結果中的最後一個,依 lastname 排序。
Optional<Person> match = repository.findBy(example,
    q -> q
        .sortBy(Sort.by("lastname").descending())
        .first()
);