在Spring Data Rest响应中选择性地扩展关联 [英] Selectively expand associations in Spring Data Rest response

查看:88
本文介绍了在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 GETs 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 call projectionConfiguration().addProjection(…) manually (by extending RepositoryRestMvcConfiguration and overriding configureRepositoryRestConfiguration(…)).

这将导致为域类型公开的资源接受具有投影名称的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 项目中找到.参见

An example of that can also be found in the Spring RESTBucks project. See the OrderProjection for the interface definition.

这篇关于在Spring Data Rest响应中选择性地扩展关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆