在 Spring Data Rest 响应中选择性地扩展关联
我有一个标准的 Spring 数据 JPA 和 Spring 数据 Rest 设置,它们正确地将关联作为指向正确资源的链接返回.
I have a standard Spring data JPA and Spring data Rest setup which, correctly, returns associations as links to the correct resources.
{
"id": 1,
"version": 2,
"date": "2011-11-22",
"description": "XPTO",
"_links": {
"self": {
"href": "http://localhost:8000/api/domain/1"
},
"otherDomain": {
"href": "http://localhost:8000/api/domain/1/otherDomain"
}
}
}
但是,在 一些 请求中,我希望扩展与otherDomain"的关联(因此客户端不必执行 N+1 次请求即可获取完整数据).
However in some requests i would like to have the association to the "otherDomain" expanded (so the client does not have to do N+1 requests to get the full data).
是否可以配置 Spring Data Rest 以这种方式处理响应?
Is it possible to configure Spring Data Rest to handle the response in this way?
推荐答案
默认响应必须保持不变,以确保 PUT
请求的负载与 GET 的负载对称
的回报.但是,Spring Data REST 引入了一个称为投影的功能(有关详细信息,请参阅 JIRA 票证)其工作原理如下:
The default responses will have to stay the same to make sure the payloads for PUT
requests are symmetric to the ones GET
s return. However, Spring Data REST introduces a feature called projections (see the JIRA ticket for details) that works as follows:
您创建一个专用接口并添加您想要包含在响应中的所有属性:
You create a dedicated interface and add all properties that you want to include in the response:
public interface MyProjection {
String getMyProperty();
MyRelatedObject getOtherDomain();
}
你可以
- 使用
@Projection
注释接口并将其放置在与域类型或其子包相同的包中 - 或者您使用
RepositoryRestConfiguration
手动注册投影并手动调用projectionConfiguration().addProjection(…)
(通过扩展RepositoryRestMvcConfiguration
并覆盖configureRepositoryRestConfiguration(…)
).
- annotate the interface using
@Projection
and place it in the very same package as the domain type or a subpackage of it - or you manually register the projection using the
RepositoryRestConfiguration
and callprojectionConfiguration().addProjection(…)
manually (by extendingRepositoryRestMvcConfiguration
and overridingconfigureRepositoryRestConfiguration(…)
).
这将导致为域类型公开的资源接受带有投影名称的 projection
参数(名称也可配置 ProjectionConfiguration
).如果给定,我们将跳过默认渲染(包括渲染相关实体的链接而不是嵌入它们)并让 Jackson 渲染支持给定接口的代理.
This will cause the resources exposed for the domain type to accept a projection
parameter (name also configurable ProjectionConfiguration
) with the name of the projection. If given, we will skip the default rendering (which includes rendering links to related entities instead of embedding them) and let Jackson render a proxy backing the given interface.
在 Spring RESTBucks 项目中也可以找到一个示例.请参阅 OrderProjection
用于接口定义.
An example of that can also be found in the Spring RESTBucks project. See the OrderProjection
for the interface definition.
相关文章