通过JPARepsitory存储库使用Spring,我有两个实体具有一对多的关系。
@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时,我希望
{
"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)但不是两者的混合。
发布于 2017-05-11 14:38:42
http://localhost:8080/api/items/5/owner指的是所谓的关联资源。它没有指向“真正的”所有者资源。
它的目的是处理联想。例如,用DELETE发送请求只会从项目中删除所有者,而不会删除实际所有者实体。
根据配置,您可以获得嵌入的所有者的所有属性。这就是你作为content得到的。
https://stackoverflow.com/questions/43903275
复制相似问题