使集合属性呈现为关系而不是 json HAL 表示中的属性 [英] Make collection propertie render as relation instead of property in json HAL representaion
问题描述
我得到了 hal 格式的响应:
I got hal formatted response as this:
{
"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 以及链接 friends.恕我直言,它们应该都是关联链接(请参阅 2.4. 创建关联),其中我可以放置"其他资源吗.
I see there property bookPublishers and also in links friends. Imho they should be both association links (see 2.4. Creating the Associations) where can I "put" another resources.
我想让 spring 渲染 bookPublishers 和朋友一样.
I would like to make spring render bookPublishers same as friends.
示例项目在这里:https://github.com/luvarqpp/poc-springHalRelations
你可以这样做:
git clone https://github.com/luvarqpp/poc-springHalRelations.git
cd poc-springHalRelations
mvn clean spring-boot:run
PS:额外的问题,为业务逻辑提供自己的关系的最简单方法是什么,例如关系renameAuthor".
PS: Bonus question, what is easiest way to provide own relation for business logic, like relation "renameAuthor" for example.
推荐答案
对于集合关系,当相关类型的存储库存在时,Spring Data 将提供一个链接.如果不存在存储库,则集合将内联在响应中,否则,客户端将如何获取数据.
For collection relationships, Spring Data will provide a link when a repository exists for the relevant type. Where no repository exists then the collection will be in-lined in the response, otherwise, how else will the client get the data.
因此,为您的 BookPublisher 类型创建一个存储库.
Therefore, create a repository for your BookPublisher type.
相关文档部分引用:
负责创建指向引用实体(例如对象的 JSON 表示中 _links 属性下的那些对象)的链接的组件.它接受一个@Entity 并遍历其属性,为存储库管理的那些属性创建链接,并在任何嵌入的或简单的属性之间进行复制.
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.
您还可以在需要时创建一个内嵌数据的投影.客户端可以在请求中指定此投影,从而防止额外的服务器调用.
You can also create a projection that would in-line the data when required. Clients could specify this projection in the request therefore preventing an additional server call.
例如
/publisher/1?projection=withBookPublishers.
/publisher/1?projection=withBookPublishers.
这篇关于使集合属性呈现为关系而不是 json HAL 表示中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!