查詢示例

簡介

本章介紹了查詢示例(Query by Example)並解釋瞭如何使用它。

查詢示例(Query by Example,簡稱 QBE)是一種使用者友好的查詢技術,介面簡潔。它允許動態建立查詢,並且不需要您編寫包含欄位名稱的查詢。實際上,查詢示例根本不需要您使用特定於儲存的查詢語言來編寫查詢。

本章解釋了查詢示例的核心概念。資訊來源於 Spring Data Commons 模組。根據您使用的資料庫,字串匹配的支援可能受到限制。

用法

查詢示例 API 由四部分組成

  • Probe(探測):帶有填充欄位的領域物件的實際示例。

  • ExampleMatcherExampleMatcher 包含有關如何匹配特定欄位的詳細資訊。它可以在多個 Example 中重用。

  • Example:一個 Example 由 probe 和 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 值的欄位將被忽略,字串則使用特定於儲存的預設設定進行匹配。

將屬性包含到查詢示例條件中基於 nullability。除非 ExampleMatcher 忽略屬性路徑,否則使用基本型別(int, double 等)的屬性總是會被包含。

可以使用 of 工廠方法或透過 ExampleMatcher 來構建 Example。Example 是不可變的。以下清單展示了一個簡單的 Example

示例 1. 簡單 Example
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 Matcher

Example 不限於預設設定。您可以使用 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 期望 probe 上設定的所有值都匹配。如果您想獲取與隱式定義的任何謂詞匹配的結果,請使用 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 和屬性路徑

值轉換

屬性路徑

流暢 API

QueryByExampleExecutor 提供了另一個我們之前沒有提及的方法:<S extends T, R> R findBy(Example<S> example, Function<FluentQuery.FetchableFluentQuery<S>, R> queryFunction)。與其他方法一樣,它執行從 Example 派生的查詢。然而,透過第二個引數,您可以控制執行的各個方面,這是否則無法動態控制的。您可以透過在第二個引數中呼叫 FetchableFluentQuery 的各種方法來實現這一點。sortBy 允許您指定結果的排序。as 允許您指定希望結果轉換為的型別。project 限制查詢的屬性。firstfirstValueoneoneValueallpagestreamcountexists 定義您獲得的結果型別以及當結果數量超出預期時查詢的行為。

使用流暢 API 獲取潛在的多個結果中的最後一個,按 lastname 排序。
Optional<Person> match = repository.findBy(example,
    q -> q
        .sortBy(Sort.by("lastname").descending())
        .first()
);