Spring引导数据休息后实体

时间:2017-12-20 15:23:30

标签: spring spring-mvc spring-boot

我有一个Spring 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 ...]的所有组合。

1 个答案:

答案 0 :(得分: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) {

您可能根本不需要传递请求正文,具体取决于该方法的作用。