首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当通过关联链接访问时,为什么包含在内容对象中的实体具有Spring数据REST?

当通过关联链接访问时,为什么包含在内容对象中的实体具有Spring数据REST?
EN

Stack Overflow用户
提问于 2017-05-10 21:49:59
回答 1查看 379关注 0票数 3

通过JPARepsitory存储库使用Spring,我有两个实体具有一对多的关系。

代码语言:javascript
复制
@Entity
class Owner {

    // owner attributes...

    @OneToMany
    Set<Item> items;
}

代码语言:javascript
复制
@Entity
class Item {

    // item attributes...

    @ManyToOne
    Owner owner;
}    

安装程序是id 1的所有者,它有一个id 5的项。

当我打电话给http://localhost:8080/api/items/5时,我得到了这样的信息

代码语言:javascript
复制
{
  // 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

代码语言:javascript
复制
{
  "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),则会得到以下内容

代码语言:javascript
复制
{
  // 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时,我希望

代码语言:javascript
复制
{
  "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"
    }
  }
}

代码语言:javascript
复制
{
  // 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)

但不是两者的混合。

EN

回答 1

Stack Overflow用户

发布于 2017-05-11 14:38:42

http://localhost:8080/api/items/5/owner指的是所谓的关联资源。它没有指向“真正的”所有者资源。

它的目的是处理联想。例如,用DELETE发送请求只会从项目中删除所有者,而不会删除实际所有者实体。

根据配置,您可以获得嵌入的所有者的所有属性。这就是你作为content得到的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43903275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档