【问题标题】:spring boot rest api mongodb update entityspring boot rest api mongodb更新实体
【发布时间】:2018-02-11 14:06:03
【问题描述】:

我在更新我的实体时遇到问题。我已经休息了 api,我使用请求映射“/people/{id}”和 PUT 方法。如果我提出请求,我会收到这样的错误 ->“写入失败,错误代码 11000 和错误消息 'E11000 重复密钥错误集合:...”

问题出在哪里?我使用 mongo 数据库。代码如下:

@PutMapping("/people/{id}")
public ResponseEntity<Person> updatePerson(@PathVariable String id, 
@Valid @RequestBody Person person) {
Optional<Person> personToUpdate = 
Optional.ofNullable(this.personRepository.findOne(id));
if(!personToUpdate.isPresent()) {
    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
if(personToUpdate.get().getName() != null) {
    personToUpdate.get().setName(person.getName());

}
if(personToUpdate.get().getSurname() != null) {
    personToUpdate.get().setSurname(person.getSurname());

}
if(personToUpdate.get().getBirthDate() != null) {
    personToUpdate.get().setBirthDate(person.getBirthDate());
}
if(personToUpdate.get().getDateOfDeath() != null) {
    personToUpdate.get().setDateOfDeath(person.getDateOfDeath());
}
if(personToUpdate.get().getGraveId() != null) {
    personToUpdate.get().setGraveId(person.getGraveId());
}

Person updatedPerson = this.personRepository.insert(personToUpdate.get());

return new ResponseEntity<>(updatedPerson, HttpStatus.OK);

}

【问题讨论】:

    标签: spring mongodb rest


    【解决方案1】:

    错误消息是说已经有同一个人的记录。 换句话说,您已经有一个具有输入属性的人。尝试更改您的请求正文。

    【讨论】:

      【解决方案2】:

      这是罪魁祸首

      Person updatedPerson = this.personRepository.insert(personToUpdate.get();
      

      您使用的是插入而不是保存。你应该这样做

      Person updatedPerson = this.personRepository.save(personToUpdate.get();
      

      insertsave 之间存在差异。简单来说。
      save相当于插入或更新。
      insert只是插入。

      因此,如果您使用插入,它会尝试插入新记录(这没关系,如果您不指定 id),但您指定的 id 会导致重复键。

      【讨论】:

      • 好的,但是如果不提供所有必填字段,它会在 json 中给我 NULL,为什么以及如何更改它?
      • 你说的是哪个json
      • 好的,没有问题。你认为像我上面写的那样在 null 之前检查字段是个好主意吗?如果没有太多的 if,还有什么更快更好看的想法吗?
      • 嗯,这取决于。如果您相信来自 PUT 的新对象具有所有必需的字段,那么您只需从数据库对象中获取 id 字段,然后将其添加到您的新对象中并保存。但是如果来自 PUT 的对象没有所有字段或数据库中的对象有一些字段为空,那么你必须做你现在正在做的事情。
      • 好的,这样我上面已经完成了,有没有更好的办法来替换这个太多的 if ?
      猜你喜欢
      • 2020-09-07
      • 2019-05-15
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 2021-08-28
      • 2019-03-11
      • 1970-01-01
      相关资源
      最近更新 更多