Spring Data 扩展
本节文档介绍了 Spring Data 的一组扩展,这些扩展使得 Spring Data 能够在各种上下文中使用。目前,大部分集成主要面向 Spring MVC。
Querydsl 扩展
Querydsl 是一个框架,通过其流式 API 实现静态类型化 SQL-like 查询的构建。
Querydsl 的维护速度已经放缓,社区已在 OpenFeign 下 fork 了该项目,地址为 github.com/OpenFeign/querydsl (groupId io.github.openfeign.querydsl )。Spring Data 在力所能及的范围内支持此 fork。 |
几个 Spring Data 模块通过 QuerydslPredicateExecutor
提供 Querydsl 集成,如下例所示
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
,如下例所示
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 添加到 classpath 中。其中一些甚至提供与 Spring HATEOAS 的集成。通常,通过在 JavaConfig 配置类中使用 @EnableSpringDataWebSupport
注解来启用集成支持,如下例所示
-
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 支持
上一节所示的配置注册了一些基本组件
-
一个 使用
DomainClassConverter
类,以便 Spring MVC 可以从请求参数或路径变量中解析由 repository 管理的领域类实例。 -
HandlerMethodArgumentResolver
实现,以便 Spring MVC 可以从请求参数中解析Pageable
和Sort
实例。 -
Jackson Modules,用于序列化/反序列化
Point
和Distance
等类型,或者根据使用的 Spring Data 模块序列化/反序列化特定于存储的类型。
使用 DomainClassConverter
类
DomainClassConverter
类允许您直接在 Spring MVC 控制器方法签名中使用领域类型,这样您就不必手动通过 repository 查找实例,如下例所示
@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
实例。此注册使 Pageable
和 Sort
成为有效的控制器方法参数,如下例所示
@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
实例
|
您想检索的页码。从 0 开始索引,默认为 0。 |
|
您想检索的页大小。默认为 20。 |
|
应按何种格式 |
要自定义此行为,请注册一个实现 PageableHandlerMethodArgumentResolverCustomizer
接口或 SortHandlerMethodArgumentResolverCustomizer
接口的 bean。其 customize()
方法将被调用,允许您更改设置,如下例所示
@Bean SortHandlerMethodArgumentResolverCustomizer sortCustomizer() {
return s -> s.setPropertyDelimiter("<-->");
}
如果设置现有 MethodArgumentResolver
的属性不足以满足您的需求,可以扩展 SpringDataWebConfiguration
或支持 HATEOAS 的等效类,覆盖 pageableResolver()
或 sortResolver()
方法,并导入您的自定义配置文件,而不是使用 @Enable
注解。
如果您需要从请求中解析多个 Pageable
或 Sort
实例(例如,针对多个表),您可以使用 Spring 的 @Qualifier
注解来区分它们。然后请求参数必须以 ${qualifier}_
为前缀。以下示例显示了最终的方法签名
String showUsers(Model model,
@Qualifier("thing1") Pageable first,
@Qualifier("thing2") Pageable second) { … }
您必须填充 thing1_page
、thing2_page
等。
传递给方法的默认 Pageable
相当于一个 PageRequest.of(0, 20)
,但您可以通过在 Pageable
参数上使用 @PageableDefault
注解来自定义它。
为 Page
创建 JSON 表示
Spring MVC 控制器通常会尝试最终向客户端渲染 Spring Data page 的表示。虽然可以直接从 handler 方法返回 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);
}
}
Page 和 Slice 的超媒体支持
Spring HATEOAS 附带了一种表示模型类 (PagedModel
/SlicedModel
),它允许用必要的 Page
/Slice
元数据以及链接来丰富 Page
或 Slice
实例的内容,以便客户端轻松导航页面。将 Page
转换为 PagedModel
是由 Spring HATEOAS RepresentationModelAssembler
接口的一个实现完成的,称为 PagedResourcesAssembler
。类似地,Slice
实例可以使用 SlicedResourcesAssembler
转换为 SlicedModel
。以下示例展示了如何将 PagedResourcesAssembler
用作控制器方法参数,SlicedResourcesAssembler
的工作方式完全相同
@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
可能会根据 page 的状态附加prev
和next
链接。这些链接指向方法映射到的 URI。添加到方法的 pagination 参数与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 Module,用于 Spring Data 领域中使用的类型,例如 org.springframework.data.geo.Distance
和 org.springframework.data.geo.Point
。
一旦启用了 Web 支持 并且 com.fasterxml.jackson.databind.ObjectMapper
可用,就会导入这些 Modules。
在初始化期间,基础设施会检测到 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
各个模块可能会提供额外的 |
Web 数据绑定支持
您可以使用 Spring Data projections(在 Projections 中描述)通过使用 JSONPath 表达式(需要 Jayway JsonPath)或 XPath 表达式(需要 XmlBeam)来绑定传入的请求负载,如下例所示
@ProjectedPayload
public interface UserPayload {
@XBRead("//firstname")
@JsonPath("$..firstname")
String getFirstname();
@XBRead("/lastname")
@JsonPath({ "$.lastname", "$.user.lastname" })
String getLastname();
}
您可以使用前面示例中所示的类型作为 Spring MVC handler 方法参数,或者通过在 RestTemplate
的方法上使用 ParameterizedTypeReference
。前面的方法声明会尝试在给定文档的任何位置查找 firstname
。lastname
的 XML 查找在传入文档的顶层执行。JSON 变体首先尝试顶层的 lastname
,但如果前者未返回值,也会尝试嵌套在 user
子文档中的 lastname
。通过这种方式,可以轻松缓解源文档结构的变化,而无需调用暴露方法(通常是基于类负载绑定的缺点)的客户端进行更改。
嵌套 projections 的支持如 Projections 中所述。如果方法返回复杂、非接口的类型,则使用 Jackson ObjectMapper
来映射最终值。
对于 Spring MVC,只要 @EnableSpringDataWebSupport
处于活动状态且 classpath 中存在所需依赖项,就会自动注册必要的转换器。对于与 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"))
当 classpath 中找到 Querydsl 时,此功能会随同 @EnableSpringDataWebSupport 自动启用。 |
在方法签名中添加 @QuerydslPredicate
提供了一个即用型的 Predicate
,您可以使用 QuerydslPredicateExecutor
运行它。
类型信息通常从方法的返回类型解析。由于该信息不一定与领域类型匹配,因此最好使用 QuerydslPredicate 的 root 属性。 |
以下示例展示了如何在方法签名中使用 @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
。
您可以通过 `@QuerydslPredicate` 的 bindings
属性自定义这些绑定,或者通过使用 Java 8 default methods
并将 QuerydslBinderCustomizer
方法添加到 repository 接口来实现,如下所示
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 | 在 repository 接口上定义的 QuerydslBinderCustomizer 会被自动检测到,并快捷方式替代 @QuerydslPredicate(bindings=…) 。 |
3 | 定义 username 属性的绑定,使其成为一个简单的 contains 绑定。 |
4 | 定义 String 属性的默认绑定,使其成为不区分大小写的 contains 匹配。 |
5 | 从 Predicate 解析中排除 password 属性。 |
您可以注册一个持有默认 Querydsl 绑定的 QuerydslBinderCustomizerDefaults bean,然后在应用来自 repository 或 @QuerydslPredicate 的特定绑定之前使用。 |
Repository 填充器
如果您使用 Spring JDBC 模块,您可能熟悉使用 SQL 脚本填充 DataSource
的支持。在 repositories 级别也有类似的抽象,尽管它不使用 SQL 作为数据定义语言,因为它必须是存储无关的。因此,填充器支持 XML(通过 Spring 的 OXM 抽象)和 JSON(通过 Jackson)来定义用于填充 repositories 的数据。
假设您有一个名为 data.json
的文件,内容如下
[ { "_class" : "com.acme.Person",
"firstname" : "Dave",
"lastname" : "Matthews" },
{ "_class" : "com.acme.Person",
"firstname" : "Carter",
"lastname" : "Beauford" } ]
您可以使用 Spring Data Commons 中提供的 repository 命名空间的填充器元素来填充您的 repositories。要将前面的数据填充到您的 PersonRepository
,请声明一个类似于以下的填充器
<?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
属性来确定的。基础设施最终会选择适当的 repository 来处理已反序列化的对象。
要改为使用 XML 定义用于填充 repositories 的数据,可以使用 unmarshaller-populator
元素。您将其配置为使用 Spring OXM 中可用的一种 XML marshaller 选项。详细信息请参阅 Spring 参考文档。以下示例展示了如何使用 JAXB 反序列化一个 repository 填充器
<?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>