使集合属性呈现为关系而不是 json HAL 表示中的 属性

Make collection propertie render as relation instead of property in json HAL representaion

我得到了 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"
    }
  }
}

我在 属性 bookPublishersfriends 链接中看到了。恕我直言,它们应该都是关联链接(请参阅 2.4. Creating the Associations)我在哪里可以 "put" 其他资源。

我想让 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 当存在相关类型的存储库时,数据将提供 link。如果不存在存储库,则集合将在响应中 in-lined,否则,客户端将如何获取数据。

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

相关documentation部分引用:

the component responsible for creating the links to referenced entities (such as those objects under the _links property in the object’s JSON representation). It takes an @Entity and iterates over its properties, creating links for those properties that are managed by a Repository and copying across any embedded or simple properties.

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

例如

/publisher/1?projection=withBookPublishers.

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