【问题标题】:Spring boot data rest post entitySpring Boot 数据休息后实体
【发布时间】:2018-06-03 05:00:06
【问题描述】:

我有一个带有以下方法的弹簧 RepositoryRestController:

@RequestMapping(method = RequestMethod.POST, value = "/doSomethingWithEntity")
    public @ResponseBody ResponseEntity deleteEmployeeSalaryPosition(@RequestBody Resource<Entity> entity)

我想将现有实体发布到此端点。

例如 Entity 类如下所示:

public Entity {
Long id;

String firstField;

String secondField;

EntityB relatedEntity;

}

将以下 JSON 发布到端点

{
  id: 1,
  firstField: "someThing",
  secondField: "BUMP",
  relatedEntity: "<root>/api/entityB/1:
}

将导致端点反序列化为实体的实例,其字段中具有以下值

Entity:
  id = null
  firstfield = "someThing"
  secondField = "BUMP",
  relatedEntity = instance of EntityB.class with everything related

我的期望是:

Entity:
  id = 1
  firstfield = "someThing"
  secondField = "BUMP",
  relatedEntity = instance of EntityB.class with everything related

问题是如何用值填充 id?

我尝试了 _links[self, entity...] 的所有组合。

【问题讨论】:

    标签: spring spring-mvc spring-boot


    【解决方案1】:

    一般来说,很多 java-ish 框架不会绑定在 JSON 中传递的 id。通常 id 在路径中。您想传递 id 然后在存储库中查找它。

    看起来 RepositoryRestController delete 应该使用 HTTP DELETE 调用,路径中的 id 为:https://docs.spring.io/spring-data/rest/docs/1.0.x/api/org/springframework/data/rest/webmvc/RepositoryRestController.html

    但无论如何,对于您的示例,您希望将 id 放在路径中:

    @RequestMapping(method = RequestMethod.POST, value = "/doSomethingWithEntity/{id}")
    @ResponseBody
        public ResponseEntity deleteEmployeeSalaryPosition(@PathVariable Long id, @RequestBody Resource<Entity> entity) {
    

    根据该方法的作用,您可能根本不需要传递请求正文。

    【讨论】:

    • 这是正确的。但是,如果我们遵循这样的想法,即在客户端没有 id 只暴露自己的 url。你知道如何说服弹簧靴帮我从关系中恢复吗?
    • 反之亦然,exposingIds 用于发送给客户端,但我想要实现的是从带有 id 的 JSON 反序列化对象。
    猜你喜欢
    • 1970-01-01
    • 2018-05-28
    • 2015-12-22
    • 2016-08-06
    • 2021-10-28
    • 1970-01-01
    • 2018-11-06
    • 2019-07-10
    • 1970-01-01
    相关资源
    最近更新 更多