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 包在類路徑中。其中一些甚至提供了與 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 註解註冊了一些元件。我們將在本節後面討論這些元件。它還檢測類路徑中的 Spring HATEOAS,併為其註冊整合元件(如果存在)。

基本 Web 支援

在 XML 中啟用 Spring Data Web 支援

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

  • 一個使用 DomainClassConverter,讓 Spring MVC 可以從請求引數或路徑變數中解析倉庫管理的領域類例項。

  • HandlerMethodArgumentResolver 實現,讓 Spring MVC 可以從請求引數中解析 PageableSort 例項。

  • Jackson 模組,用於序列化/反序列化 PointDistance 等型別,或儲存特定型別,具體取決於使用的 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 的 HandlerMethodArgumentResolvers

上一節 中顯示的配置片段還註冊了一個 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=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),但您可以使用 @PageableDefault 註解在 Pageable 引數上進行自定義。

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 的簡化版本(Spring Data 的版本位於 org.springframework.data.web 包中)。它可用於包裝 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 欄位,暴露了基本的 pagination 元資料。

全域性啟用簡化的 Page 渲染

如果您不想修改所有現有控制器以新增對映步驟,從返回 Page 改為返回 PagedModel,您可以透過如下方式調整 @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);
  }
}

PageSlice 的超媒體支援

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

將 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 封套格式不遵循任何正式指定的結構,並且不保證穩定,我們可能隨時更改它。強烈建議啟用渲染為支援超媒體的官方媒體型別,例如 HAL,Spring HATEOAS 支援此型別。可以透過使用其 @EnableHypermediaSupport 註解來啟用這些型別。更多資訊請參見Spring HATEOAS 參考文件

組裝器生成了正確的 URI,並採用了預設配置將引數解析為即將到來的請求的 Pageable。這意味著,如果您更改該配置,連結會自動遵循更改。預設情況下,組裝器指向呼叫它的控制器方法,但您可以透過傳遞一個自定義 Link 作為構建 pagination 連結的基礎來自定義這一點,這過載了 PagedResourcesAssembler.toModel(…) 方法。

Spring Data Jackson 模組

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

在初始化期間,基礎設施會載入 SpringDataJacksonModules(例如 SpringDataJacksonConfiguration),以便將宣告的 com.fasterxml.jackson.databind.Module 提供給 Jackson ObjectMapper

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

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 處於活動狀態且類路徑中存在所需依賴項,就會自動註冊必要的轉換器。對於與 RestTemplate 一起使用,請手動註冊 ProjectingJackson2HttpMessageConverter (JSON) 或 XmlBeamHttpMessageConverter

更多資訊,請參閱規範的Spring Data Examples repository 中的web projection example

Querydsl Web 支援

對於支援Querydsl 整合的儲存,您可以從 Request 查詢字串中包含的屬性派生查詢。

考慮以下查詢字串

?firstname=Dave&lastname=Matthews

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

QUser.user.firstname.eq("Dave").and(QUser.user.lastname.eq("Matthews"))
當類路徑中找到 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 將查詢字串引數解析為匹配 UserPredicate

預設繫結如下

  • 簡單屬性上的 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 屬性。
您可以註冊一個 QuerydslBinderCustomizerDefaults bean,該 bean 在應用倉庫或 @QuerydslPredicate 的特定繫結之前持有預設的 Querydsl 繫結。

倉庫填充器

如果您使用 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>