如何在 Spring Data REST 资源中返回关联的表示


有以下网址 -/users/2/

profile ,/users/2/userPosts

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

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

一个例子会有所帮助

您可能更想研究Spring Data REST的投影功能,该功能允许您使用本博客文章中描述的接口来制作自定义响应。

由于这两个属性(profileuserPosts)似乎是用户项资源的关联,因此执行以下操作就足够了:

@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 参数传递给公开的资源,以查看扩展的表示形式。

或者,您可以为ProfilePost创建这些类型的接口,并在存储库上为这两种类型配置@RepositoryRestResource以包含excerptProjection = YourProjectionInterface.class 。这将导致每当响应中包含关联时呈现投影(即可以嵌入实际链接到的资源)。

最新更新