简体   繁体   中英

spring boot rest api mongodb update entity

I've a problem with updating my entity. I've rest api where I use request mapping "/people/{id}" with PUT method. If I make a request I get an error like this -> "Write failed with error code 11000 and error message 'E11000 duplicate key error collection:..."

Where is the problem ? I use mongo database. Code below:

@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);

}

This is the culprit

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

You are using insert instead of save. You should be doing

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

There is difference between insert and save . In simple terms.
save is equivalent to insert or update.
insert is just insert.

Hence if you use insert, it tries to insert a new record(This is okay, if you don't specify the id), but you are specifying id which results in duplicate key.

The error message is saying that there's already a record with the same person. In other words, you already have a person with the input attributes. Try to change your request body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM