通过 JPARepsitory
使用 Spring Data REST存储库,我有两个具有一对多关系的实体。
@Entity
class Owner {
// owner attributes...
@OneToMany
Set<Item> items;
}
和
@Entity
class Item {
// item attributes...
@ManyToOne
Owner owner;
}
设置是 id 为 1 的所有者有一个 id 为 5 的项目。
当我调用 http://localhost:8080/api/items/5
我得到类似的东西
{
// item attributes
"_links": {
"self": {
"href": "http://localhost:8080/api/items/5"
},
"item": {
"href": "http://localhost:8080/api/items/5"
},
"owner": {
"href": "http://localhost:8080/api/items/5/owner"
}
}
}
然后,当我调用 http://localhost:8080/api/items/5/owner
我明白了
{
"content": {
// owner attributes
},
"_links": {
"self": {
"href": "http://localhost:8080/api/owners/1"
},
"owner": {
"href": "http://localhost:8080/api/owners/1"
},
"items": {
"href": "http://localhost:8080/api/owners/1/items"
}
}
}
但是,如果我调用 http://localhost:8080/api/owners/1
(这是同一个实体,但在身份 href 而不是关联 href)我得到类似的东西
{
// owner attributes
"_links": {
"self": {
"href": "http://localhost:8080/api/owners/1"
},
"owner": {
"href": "http://localhost:8080/api/owners/1"
},
"items": {
"href": "http://localhost:8080/api/owners/1/items"
}
}
}
在这里,所有者被包裹在一个额外的 content
中从单个关联资源调用时的对象。
更新澄清
如果我调用 self
,我希望href 我会得到完全相同的表示,但在这种情况下我不会。我得到规范的实体表示。
我的问题是,为什么会这样?如果通过关联资源返回的实体具有 self
href 是从中检索到实体的 URI,或者通过关联资源返回的实体是否应该与实体的项资源具有相同的表示形式?
简而言之,当我调用 http://localhost:8080/api/items/5/owner
我希望得到 p>
{
"content": {
// owner attributes
},
"_links": {
"self": {
"href": "http://localhost:8080/api/items/5/owner"
// ^^^ the URI that was retrieved that will always return this representation
},
"owner": {
"href": "http://localhost:8080/api/owners/1"
// ^^^ the canonical entity URI
},
"items": {
"href": "http://localhost:8080/api/owners/1/items"
}
}
}
或
{
// owner attributes
"_links": {
"self": {
"href": "http://localhost:8080/api/owners/1"
},
"owner": {
"href": "http://localhost:8080/api/owners/1"
},
"items": {
"href": "http://localhost:8080/api/owners/1/items"
}
}
}
// ^^^ The canonical entity representation (no "content" wrapper)
但不是两者的混合。
最佳答案
http://localhost:8080/api/items/5/owner
指的是所谓的 association resource .它不指向“真正的”所有者资源。
它的目的是处理关联。例如。发送带有 DELETE
的请求只会从项目中删除所有者,但不会删除实际所有者实体。
根据配置,您可以获得嵌入所有者的所有属性。这就是您作为 content
获得的内容。
关于java - 当通过关联链接访问时,为什么实体包含在 Spring Data REST 的内容对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43903275/