Spring Data 擴充套件

本節介紹了 Spring Data 的一組擴充套件,這些擴充套件使得 Spring Data 可以在各種環境中使用。目前,大部分整合主要針對 Spring MVC。

Querydsl 擴充套件

Querydsl 是一個框架,它透過其流暢的 API 實現靜態型別的類 SQL 查詢構造。

Querydsl 的維護速度已放緩,社群已在 OpenFeign 下分支了該專案,位於 github.com/OpenFeign/querydsl(groupId io.github.openfeign.querydsl)。Spring Data 會盡力支援該分支。

幾個 Spring Data 模組透過 QuerydslPredicateExecutor 提供了與 Querydsl 的整合,如下例所示

QuerydslPredicateExecutor 介面
public interface QuerydslPredicateExecutor<T> {

  Optional<T> findById(Predicate predicate);  (1)

  Iterable<T> findAll(Predicate predicate);   (2)

  long count(Predicate predicate);            (3)

  boolean exists(Predicate predicate);        (4)

  // … more functionality omitted.
}
1 查詢並返回與 Predicate 匹配的單個實體。
2 查詢並返回與 Predicate 匹配的所有實體。
3 返回與 Predicate 匹配的實體數量。
4 返回是否存在與 Predicate 匹配的實體。

要使用 Querydsl 支援,請在您的儲存庫介面上擴充套件 QuerydslPredicateExecutor,如下例所示

Querydsl 在儲存庫上的整合
interface UserRepository extends CrudRepository<User, Long>, QuerydslPredicateExecutor<User> {
}

前面的例子展示瞭如何使用 Querydsl 的 Predicate 例項編寫型別安全的查詢,如下例所示

Predicate predicate = user.firstname.equalsIgnoreCase("dave")
	.and(user.lastname.startsWithIgnoreCase("mathews"));

userRepository.findAll(predicate);

Web 支援

支援儲存庫程式設計模型的 Spring Data 模組提供了多種 Web 支援。Web 相關元件需要 Spring MVC JAR 包在 classpath 中。其中一些甚至提供了與 Spring HATEOAS 的整合。通常,透過在 JavaConfig 配置類中使用 @EnableSpringDataWebSupport 註解來啟用整合支援,如下例所示

啟用 Spring Data Web 支援
  • Java

  • XML

@Configuration
@EnableWebMvc
@EnableSpringDataWebSupport
class WebConfiguration {}
<bean class="org.springframework.data.web.config.SpringDataWebConfiguration" />

<!-- If you use Spring HATEOAS, register this one *instead* of the former -->
<bean class="org.springframework.data.web.config.HateoasAwareSpringDataWebConfiguration" />

@EnableSpringDataWebSupport 註解會註冊一些元件。我們將在本節後面討論這些元件。它還會檢測 classpath 中是否存在 Spring HATEOAS,併為其註冊整合元件(如果存在)。

基本 Web 支援

在 XML 中啟用 Spring Data Web 支援

上一節中展示的配置註冊了一些基本元件

  • 一個 使用 DomainClassConverter 用於讓 Spring MVC 從請求引數或路徑變數解析儲存庫管理的領域類例項。

  • HandlerMethodArgumentResolver 實現,用於讓 Spring MVC 從請求引數解析 PageableSort 例項。

  • 用於序列化/反序列化 PointDistance 等型別或特定儲存相關型別的 Jackson 模組,具體取決於使用的 Spring Data 模組。

使用 DomainClassConverter

DomainClassConverter 類允許您直接在 Spring MVC 控制器方法的簽名中使用領域型別,這樣您就不需要透過儲存庫手動查詢例項了,如下例所示

在方法簽名中使用領域型別的 Spring MVC 控制器
@Controller
@RequestMapping("/users")
class UserController {

  @RequestMapping("/{id}")
  String showUserForm(@PathVariable("id") User user, Model model) {

    model.addAttribute("user", user);
    return "userForm";
  }
}

該方法直接接收一個 User 例項,無需進一步查詢。透過讓 Spring MVC 首先將路徑變數轉換為領域類的 id 型別,然後透過呼叫註冊到該領域型別的儲存庫例項上的 findById(…) 方法來訪問例項,即可解析該例項。

目前,儲存庫必須實現 CrudRepository 才能被發現並進行轉換。

用於 Pageable 和 Sort 的 HandlerMethodArgumentResolver

上一節中展示的配置片段還註冊了 PageableHandlerMethodArgumentResolver 以及一個 SortHandlerMethodArgumentResolver 例項。該註冊使得 PageableSort 可以作為有效的控制器方法引數,如下例所示

使用 Pageable 作為控制器方法引數
@Controller
@RequestMapping("/users")
class UserController {

  private final UserRepository repository;

  UserController(UserRepository repository) {
    this.repository = repository;
  }

  @RequestMapping
  String showUsers(Model model, Pageable pageable) {

    model.addAttribute("users", repository.findAll(pageable));
    return "users";
  }
}

前面的方法簽名會使得 Spring MVC 嘗試使用以下預設配置從請求引數中派生一個 Pageable 例項

表 1. 用於 Pageable 例項的請求引數

page

您想檢索的頁碼。基於 0 索引,預設值為 0。

size

您想檢索的頁面大小。預設值為 20。

sort

用於排序的屬性,格式為 property,property(,ASC|DESC)(,IgnoreCase)。預設排序方向是區分大小寫的升序。如果您想切換方向或大小寫敏感性,可以使用多個 sort 引數,例如 ?sort=firstname&sort=lastname,asc&sort=city,ignorecase

要自定義此行為,請分別註冊實現 PageableHandlerMethodArgumentResolverCustomizer 介面或 SortHandlerMethodArgumentResolverCustomizer 介面的 bean。其 customize() 方法會被呼叫,允許您更改設定,如下例所示

@Bean SortHandlerMethodArgumentResolverCustomizer sortCustomizer() {
    return s -> s.setPropertyDelimiter("<-->");
}

如果設定現有 MethodArgumentResolver 的屬性不足以滿足您的需求,可以擴充套件 SpringDataWebConfiguration 或支援 HATEOAS 的對應類,覆蓋 pageableResolver()sortResolver() 方法,並匯入您自定義的配置檔案,而不是使用 @Enable 註解。

如果您需要從請求中解析多個 PageableSort 例項(例如,用於多個表格),可以使用 Spring 的 @Qualifier 註解來區分它們。請求引數必須以 ${qualifier}_ 為字首。下例展示了相應的方法簽名

String showUsers(Model model,
      @Qualifier("thing1") Pageable first,
      @Qualifier("thing2") Pageable second) { … }

您必須填寫 thing1_pagething2_page 等引數。

傳遞給方法的預設 Pageable 等同於 PageRequest.of(0, 20),但您可以透過在 Pageable 引數上使用 @PageableDefault 註解來對其進行自定義。

建立 Page 的 JSON 表示

Spring MVC 控制器通常會嘗試最終將 Spring Data 頁面的表示呈現給客戶端。雖然可以直接從處理器方法返回 Page 例項讓 Jackson 按原樣渲染,但我們強烈建議不要這樣做,因為底層實現類 PageImpl 是一個領域型別。這意味著我們可能出於不相關的原因需要或不得不更改其 API,而此類更改可能會以破壞性的方式改變最終的 JSON 表示。

從 Spring Data 3.1 開始,我們透過發出描述該問題的警告日誌來暗示這個問題。我們仍然最終建議利用與 Spring HATEOAS 的整合,這是一種完全穩定且支援超媒體的方式來渲染頁面,使客戶端能夠輕鬆導航。但從 3.3 版本開始,Spring Data 提供了一種方便使用的頁面渲染機制,它不需要包含 Spring HATEOAS。

使用 Spring Data 的 PagedModel

其核心在於支援一個簡化版的 Spring HATEOAS 的 PagedModel(位於 org.springframework.data.web 包中的 Spring Data 版本)。它可用於包裝 Page 例項,生成一個簡化表示,該表示反映了 Spring HATEOAS 建立的結構,但省略了導航連結。

import org.springframework.data.web.PagedModel;

@Controller
class MyController {

  private final MyRepository repository;

  // Constructor ommitted

  @GetMapping("/page")
  PagedModel<?> page(Pageable pageable) {
    return new PagedModel<>(repository.findAll(pageable)); (1)
  }
}
1 Page 例項包裝到 PagedModel 中。

這將生成一個如下所示的 JSON 結構

{
  "content" : [
     … // Page content rendered here
  ],
  "page" : {
    "size" : 20,
    "totalElements" : 30,
    "totalPages" : 2,
    "number" : 0
  }
}

注意文件如何包含一個 page 欄位,暴露了重要的分頁元資料。

全域性啟用簡化 Page 渲染

如果您不想更改所有現有控制器以新增對映步驟來返回 PagedModel 而不是 Page,可以透過如下修改 @EnableSpringDataWebSupport 來啟用將 PageImpl 例項自動轉換為 PagedModel

@EnableSpringDataWebSupport(pageSerializationMode = VIA_DTO)
class MyConfiguration { }

這將允許您的控制器仍然返回 Page 例項,並且它們將自動被渲染為簡化表示。

@Controller
class MyController {

  private final MyRepository repository;

  // Constructor ommitted

  @GetMapping("/page")
  Page<?> page(Pageable pageable) {
    return repository.findAll(pageable);
  }
}

對 Page 和 Slice 的超媒體支援

Spring HATEOAS 提供了一個表示模型類(PagedModel/SlicedModel),它允許用必要的 Page/Slice 元資料以及用於讓客戶端輕鬆導航頁面的連結來豐富 PageSlice 例項的內容。將 Page 轉換為 PagedModel 是透過實現 Spring HATEOAS 的 RepresentationModelAssembler 介面(稱為 PagedResourcesAssembler)來完成的。類似地,Slice 例項可以使用 SlicedResourcesAssembler 轉換為 SlicedModel。以下示例展示瞭如何在控制器方法引數中使用 PagedResourcesAssemblerSlicedResourcesAssembler 的工作方式完全相同

使用 PagedResourcesAssembler 作為控制器方法引數
@Controller
class PersonController {

  private final PersonRepository repository;

  // Constructor omitted

  @GetMapping("/people")
  HttpEntity<PagedModel<Person>> people(Pageable pageable,
    PagedResourcesAssembler assembler) {

    Page<Person> people = repository.findAll(pageable);
    return ResponseEntity.ok(assembler.toModel(people));
  }
}

啟用配置,如上例所示,使得 PagedResourcesAssembler 可以用作控制器方法引數。在其上呼叫 toModel(…) 方法會產生以下效果

  • Page 的內容成為 PagedModel 例項的內容。

  • PagedModel 物件附加一個 PageMetadata 例項,並填充來自 Page 和底層 Pageable 的資訊。

  • PagedModel 可能會附加 prevnext 連結,這取決於頁面的狀態。這些連結指向方法對映的 URI。新增到方法的 pagination 引數與 PageableHandlerMethodArgumentResolver 的設定匹配,以確保連結稍後可以被解析。

假設資料庫中有 30 個 Person 例項。您現在可以觸發一個請求(GET localhost:8080/people),並看到類似如下的輸出

{ "links" : [
    { "rel" : "next", "href" : "https://:8080/persons?page=1&size=20" }
  ],
  "content" : [
     … // 20 Person instances rendered here
  ],
  "page" : {
    "size" : 20,
    "totalElements" : 30,
    "totalPages" : 2,
    "number" : 0
  }
}
這裡顯示的 JSON 信封格式不遵循任何正式規範的結構,並且不保證穩定,我們可能隨時更改它。強烈建議啟用渲染為由 Spring HATEOAS 支援的、超媒體驅動的官方媒體型別,例如 HAL。這些可以透過使用其 @EnableHypermediaSupport 註解來啟用。在 Spring HATEOAS 參考文件 中查詢更多資訊。

assembler 生成了正確的 URI,並且也拾取了預設配置,以便將引數解析為即將到來的請求的 Pageable。這意味著,如果您更改該配置,連結將自動遵循更改。預設情況下,assembler 指向其被呼叫的控制器方法,但您可以透過傳入自定義的 Link 作為構建分頁連結的基礎來對其進行自定義,這會過載 PagedResourcesAssembler.toModel(…) 方法。

Spring Data Jackson 模組

核心模組以及一些特定儲存模組附帶了一組 Jackson 模組,用於 Spring Data 領域中使用的型別,例如 org.springframework.data.geo.Distanceorg.springframework.data.geo.Point
一旦啟用了 Web 支援 並且 com.fasterxml.jackson.databind.ObjectMapper 可用,這些模組就會被匯入。

在初始化期間,基礎設施會載入 SpringDataJacksonModules(如 SpringDataJacksonConfiguration),從而使宣告的 com.fasterxml.jackson.databind.Module 對 Jackson ObjectMapper 可用。

通用基礎設施註冊了以下領域型別的資料繫結 mixin。

org.springframework.data.geo.Distance
org.springframework.data.geo.Point
org.springframework.data.geo.Box
org.springframework.data.geo.Circle
org.springframework.data.geo.Polygon

各個模組可能提供額外的 SpringDataJacksonModules
更多詳情請參閱特定儲存部分。

Web 資料繫結支援

您可以使用 Spring Data 投影(在 投影 中描述)透過使用 JSONPath 表示式(需要 Jayway JsonPath)或 XPath 表示式(需要 XmlBeam)來繫結傳入的請求負載,如下例所示

使用 JSONPath 或 XPath 表示式進行 HTTP 負載繫結
@ProjectedPayload
public interface UserPayload {

  @XBRead("//firstname")
  @JsonPath("$..firstname")
  String getFirstname();

  @XBRead("/lastname")
  @JsonPath({ "$.lastname", "$.user.lastname" })
  String getLastname();
}

您可以使用上例中所示的型別作為 Spring MVC 處理器方法的引數,或在 RestTemplate 的某個方法上使用 ParameterizedTypeReference。前面的方法宣告將嘗試在給定文件中的任何位置查詢 firstnamelastname 的 XML 查詢在傳入文件的頂層執行。其 JSON 版本首先嚐試頂層 lastname,如果前者未返回值,則也嘗試巢狀在 user 子文件中的 lastname。這樣,無需客戶端呼叫暴露的方法(通常是基於類的負載繫結的缺點),即可輕鬆緩解源文件結構的變化。

支援巢狀投影,如 投影 中所述。如果方法返回一個複雜的非介面型別,則使用 Jackson 的 ObjectMapper 來對映最終值。

對於 Spring MVC,一旦 @EnableSpringDataWebSupport 啟用並且所需的依賴項在 classpath 中可用,必要的轉換器就會自動註冊。對於與 RestTemplate 一起使用,請手動註冊 ProjectingJackson2HttpMessageConverter (JSON) 或 XmlBeamHttpMessageConverter

更多資訊請參閱規範的 Spring Data Examples 儲存庫 中的 Web 投影示例

Querydsl Web 支援

對於那些集成了 Querydsl 的儲存,您可以從 Request 查詢字串中包含的屬性派生查詢。

考慮以下查詢字串

?firstname=Dave&lastname=Matthews

給定前例中的 User 物件,您可以使用 QuerydslPredicateArgumentResolver 將查詢字串解析為以下值,如下所示

QUser.user.firstname.eq("Dave").and(QUser.user.lastname.eq("Matthews"))
當 classpath 中找到 Querydsl 時,此功能會隨同 @EnableSpringDataWebSupport 自動啟用。

在方法簽名中新增 @QuerydslPredicate 提供了一個即用型的 Predicate,您可以使用 QuerydslPredicateExecutor 來執行它。

型別資訊通常從方法的返回型別解析。由於該資訊不一定與領域型別匹配,因此最好使用 @QuerydslPredicateroot 屬性。

以下示例展示瞭如何在方法簽名中使用 @QuerydslPredicate

@Controller
class UserController {

  @Autowired UserRepository repository;

  @RequestMapping(value = "/", method = RequestMethod.GET)
  String index(Model model, @QuerydslPredicate(root = User.class) Predicate predicate,    (1)
          Pageable pageable, @RequestParam MultiValueMap<String, String> parameters) {

    model.addAttribute("users", repository.findAll(predicate, pageable));

    return "index";
  }
}
1 將查詢字串引數解析為與 User 匹配的 Predicate

預設繫結如下

  • 簡單屬性上的 Object 作為 eq (等於)。

  • 集合型別屬性上的 Object 作為 contains (包含)。

  • 簡單屬性上的 Collection 作為 in (在其中)。

您可以透過 @QuerydslPredicatebindings 屬性自定義這些繫結,或者利用 Java 8 的 default methods 並在儲存庫介面中新增 QuerydslBinderCustomizer 方法,如下所示

interface UserRepository extends CrudRepository<User, String>,
                                 QuerydslPredicateExecutor<User>,                (1)
                                 QuerydslBinderCustomizer<QUser> {               (2)

  @Override
  default void customize(QuerydslBindings bindings, QUser user) {

    bindings.bind(user.username).first((path, value) -> path.contains(value))    (3)
    bindings.bind(String.class)
      .first((StringPath path, String value) -> path.containsIgnoreCase(value)); (4)
    bindings.excluding(user.password);                                           (5)
  }
}
1 QuerydslPredicateExecutor 提供了對 Predicate 的特定查詢方法的訪問。
2 在儲存庫介面上定義的 QuerydslBinderCustomizer 會被自動拾取,並簡化 @QuerydslPredicate(bindings=…​) 的使用。
3 定義 username 屬性的繫結為一個簡單的 contains 繫結。
4 定義 String 屬性的預設繫結為不區分大小寫的 contains 匹配。
5 Predicate 解析中排除 password 屬性。
在應用來自儲存庫或 @QuerydslPredicate 的特定繫結之前,您可以註冊一個持有預設 Querydsl 繫結的 QuerydslBinderCustomizerDefaults bean。

儲存庫填充器

如果您使用 Spring JDBC 模組,您可能熟悉使用 SQL 指令碼填充 DataSource 的支援。在儲存庫級別也有類似的抽象,儘管它不使用 SQL 作為資料定義語言,因為它必須與儲存無關。因此,填充器支援 XML(透過 Spring 的 OXM 抽象)和 JSON(透過 Jackson)來定義用於填充儲存庫的資料。

假設您有一個名為 data.json 的檔案,內容如下

在 JSON 中定義的資料
[ { "_class" : "com.acme.Person",
 "firstname" : "Dave",
  "lastname" : "Matthews" },
  { "_class" : "com.acme.Person",
 "firstname" : "Carter",
  "lastname" : "Beauford" } ]

您可以使用 Spring Data Commons 提供的儲存庫名稱空間的填充器元素來填充您的儲存庫。要將前面的資料填充到您的 PersonRepository 中,請宣告一個類似於以下的填充器

宣告一個 Jackson 儲存庫填充器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:repository="http://www.springframework.org/schema/data/repository"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/repository
    https://www.springframework.org/schema/data/repository/spring-repository.xsd">

  <repository:jackson2-populator locations="classpath:data.json" />

</beans>

前面的宣告會使得 data.json 檔案被讀取並由 Jackson ObjectMapper 進行反序列化。

JSON 物件將被解組到的型別是透過檢查 JSON 文件的 _class 屬性來確定的。基礎設施最終會選擇適當的儲存庫來處理反序列化的物件。

如果想改用 XML 來定義應該填充儲存庫的資料,可以使用 unmarshaller-populator 元素。您可以將其配置為使用 Spring OXM 中可用的 XML marshaller 選項之一。詳情請參閱 Spring 參考文件。以下示例展示瞭如何使用 JAXB 解組儲存庫填充器

宣告一個解組儲存庫填充器(使用 JAXB)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:repository="http://www.springframework.org/schema/data/repository"
  xmlns:oxm="http://www.springframework.org/schema/oxm"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/repository
    https://www.springframework.org/schema/data/repository/spring-repository.xsd
    http://www.springframework.org/schema/oxm
    https://www.springframework.org/schema/oxm/spring-oxm.xsd">

  <repository:unmarshaller-populator locations="classpath:data.json"
    unmarshaller-ref="unmarshaller" />

  <oxm:jaxb2-marshaller contextPath="com.acme" />

</beans>