如何在 Spring Data REST 资源中返回关联的表示? [英] How to return representations of associations in a Spring Data REST resource?

查看:26
本文介绍了如何在 Spring Data REST 资源中返回关联的表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有以下网址 -/users/2/profile ,/users/2/userPosts

There are following URLS - /users/2/profile , /users/2/userPosts

我需要在服务器端连接两个 Spring Data REST 结果的输出,并从它们构建单个 JSON 并在不同的 URL /users/2/custom 上发送.

I need to concat output of both Spring Data REST results in server side and build single JSON from them and send on different URL /users/2/custom.

所以,我想从 Spring MVC 对 SDR url 进行 2 次调用,我们可以使用 RestTemplate 和一些 JSON concat 实用程序来做到这一点,这里服务器和数据库在同一台机器上,所以 RestTemplate 可能会有 localhost

So, I am thinking to make 2 calls to SDR urls from Spring MVC, can we do this using RestTemplate and some JSON concat utility , here server and database is on same machine so RestTemplate will probably have localhost

一个例子会有所帮助

推荐答案

您可能更愿意研究 Spring Data REST 的投影功能,该功能允许您使用此 博文.

You might rather want to look into the projections feature of Spring Data REST which allows you to craft custom responses by using interfaces as described in this blog post.

因为这两个属性(profileuserPosts)似乎都是用户项目资源的关联,所以做这样的事情就足够了:

As both properties (profile and userPosts) seem to be associations of a user item resource it should be sufficient to do something like this:

@Projection(types = User.class)
interface UserWithDetails {

  // List getters for basic properties you want to expose…

  // Add dedicated getters for associations to be included

  Profile getProfile();

  List<Post> getUserPosts();
}

客户端现在可以将 projection 参数传递给公开的资源以查看扩展的表示.

Clients can now pass a projection parameter to the resources exposed to see the expanded representation.

作为替代方案,您可以为 ProfilePost 创建这些类型的接口,并在存储库上为这两个接口配置 @RepositoryRestResource包含 excerptProjection = YourProjectionInterface.class 的类型.这将导致在响应中包含关联时渲染投影(即可以嵌入实际链接到的资源).

As an alternative, you can create these kinds of interfaces for Profile and Post and configure @RepositoryRestResource on the repositories for both of these types to contain excerptProjection = YourProjectionInterface.class. This will cause the projections to be rendered whenever an association is included in the response (i.e. an actually-linked-to-resource could be embedded).

这篇关于如何在 Spring Data REST 资源中返回关联的表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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