首页 > 解决方案 > 使集合属性呈现为关系而不是 json HAL 表示中的属性

问题描述

我得到了 hal 格式的响应,如下所示:

{
  "name": "Publisher A",
  "bookPublishers": [
    {
      "publishedDate": "2019-07-12T08:19:04.583+0000",
      "_links": {
        "publisher": {
          "href": "http://localhost:8080/api/publishers/1"
        },
        "book": {
          "href": "http://localhost:8080/api/books/2"
        }
      }
    },
    {
      "publishedDate": "2019-07-12T08:19:04.564+0000",
      "_links": {
        "publisher": {
          "href": "http://localhost:8080/api/publishers/1"
        },
        "book": {
          "href": "http://localhost:8080/api/books/1"
        }
      }
    }
  ],
  "_links": {
    "self": {
      "href": "http://localhost:8080/api/publishers/1"
    },
    "publisher": {
      "href": "http://localhost:8080/api/publishers/1"
    },
    "friends": {
      "href": "http://localhost:8080/api/publishers/1/friends"
    },
    "createdBy": {
      "href": "http://localhost:8080/api/publishers/1/contact"
    }
  }
}

我看到那里有属性bookPublishers和链接中的朋友。恕我直言,它们应该都是关联链接(请参阅2.4. 创建关联)我可以在哪里“放置”另一个资源。

我想让 spring 渲染 bookPublishers 和朋友一样。

示例项目在这里:https ://github.com/luvarqpp/poc-springHalRelations

你可以做:

git clone https://github.com/luvarqpp/poc-springHalRelations.git
cd poc-springHalRelations
mvn clean spring-boot:run

而不是打开http://localhost:8080/api

PS:奖金问题,为业务逻辑提供自己的关系的最简单方法是什么,例如关系“renameAuthor”。

标签: spring-data-restspring-hateoas

解决方案


对于集合关系,当相关类型的存储库存在时,Spring Data 将提供一个链接。如果不存在存储库,则集合将内联在响应中,否则,客户端将如何获取数据。

因此,为您的 BookPublisher 类型创建一个存储库。

相关文档部分引用:

负责创建指向引用实体的链接的组件(例如对象的 JSON 表示中的 _links 属性下的那些对象)。它采用@Entity 并迭代其属性,为由存储库管理的那些属性创建链接,并在任何嵌入或简单属性之间进行复制。

您还可以创建一个投影,以便在需要时嵌入数据。客户端可以在请求中指定此投影,从而防止额外的服务器调用。

例如

/publisher/1?projection=withBookPublishers。

https://docs.spring.io/spring-data/rest/docs/current/reference/html/#projections-excerpts.projections


推荐阅读