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 支持,请在 Repository 接口上扩展 QuerydslPredicateExecutor,如以下示例所示

Repository 上的 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 支持

支持 Repository 编程模型的 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 可以从请求参数或路径变量解析 Repository 管理的域类的实例。

  • HandlerMethodArgumentResolver 实现,以便 Spring MVC 可以从请求参数解析 PageableSort 实例。

  • Jackson Modules 用于序列化/反序列化诸如 PointDistance 之类的类型,或存储特定类型,具体取决于所使用的 Spring Data 模块。

使用 DomainClassConverter

DomainClassConverter 类允许您直接在 Spring MVC 控制器方法签名中使用域类型,这样您就不需要手动通过 Repository 查找实例,如以下示例所示

在方法签名中使用域类型的 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 类型,然后最终通过在为域类型注册的 Repository 实例上调用 findById(…) 来访问该实例,从而解析该实例。

目前,Repository 必须实现 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 参数,例如 ?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 的简化版本(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 字段,该字段公开了基本的页面元数据。

全局启用简化的 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);
  }
}

PageSlice 的超媒体支持

Spring HATEOAS 提供了一个表示模型类(PagedModel/SlicedModel),允许使用必要的 Page/Slice 元数据以及允许客户端轻松导航页面的链接来丰富 PageSlice 实例的内容。将 Page 转换为 PagedModel 由 Spring HATEOAS RepresentationModelAssembler 接口的一个实现来完成,该实现称为 PagedResourcesAssembler。类似地,可以使用 SlicedResourcesAssemblerSlice 实例转换为 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。添加到该方法的页面参数与 PageableHandlerMethodArgumentResolver 的设置相匹配,以确保以后可以解析这些链接。

假设我们在数据库中有 30 个 Person 实例。您现在可以触发一个请求 (GET localhost:8080/people) 并查看类似于以下内容的输出:

{ "links" : [
    { "rel" : "next", "href" : "http://localhost: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 参考文档

汇编器生成了正确的 URI,并且还选择了默认配置以将参数解析为即将到来的请求的 Pageable。这意味着,如果您更改该配置,则链接会自动遵守该更改。默认情况下,汇编器指向调用它的控制器方法,但是您可以通过传递一个自定义 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

通用基础设施注册了以下域类型的数据绑定混合:

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。前面的方法声明将尝试在给定文档中的任何位置查找 firstname。XML 查找 lastname 是在传入文档的顶层执行的。该 JSON 变体首先尝试一个顶级的 lastname,但如果前者没有返回值,则也会尝试嵌套在 user 子文档中的 lastname。这样,可以轻松缓解源文档结构中的更改,而无需客户端调用公开的方法(通常是基于类的有效负载绑定的缺点)。

支持嵌套投影,如 投影中所述。如果该方法返回一个复杂的非接口类型,则使用 Jackson ObjectMapper 来映射最终值。

对于 Spring MVC,只要 @EnableSpringDataWebSupport 处于活动状态并且所需的依赖项在类路径上可用,必要的转换器就会自动注册。对于与 RestTemplate 的使用,请手动注册 ProjectingJackson2HttpMessageConverter(JSON)或 XmlBeamHttpMessageConverter

有关更多信息,请参见规范 Spring Data 示例存储库中的 Web 投影示例

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 将查询字符串参数解析为与 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 编组器选项之一。有关详细信息,请参见 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>