Kindth
Kindth

Reputation: 337

Patch REST API to Partial Update MongoDB in spring boot

I want to send a REST PATCH request to my API to only update some fields not the whole requestbody. Can someone help me to solve this issue

@PatchMapping("/update/{id}")
    public ResponseEntity<String> update(@Valid @RequestBody Ordonnance ordonnance, @PathVariable("id") String id){

        Optional<Ordonnance> ordonnanceData = ordonnanceRepository.findById(id);
       this.ordonnanceRepository.save(ordonnance);
       return ResponseEntity.ok("resource updated");
}

Upvotes: 0

Views: 2217

Answers (1)

Brice Frisco
Brice Frisco

Reputation: 450

You can modify the fields by calling setters on the object which is returned from the repository.

@PatchMapping("/update/{id}")
public ResponseEntity<String> update(@Valid @RequestBody Ordonnance ordonnance, @PathVariable("id") String id){
    Optional<Ordonnance> dbOrdonnance = ordonnanceRepository.findById(id);

    if (!ordonnanceData.isPresent()) {
      // The ID entered could not be found.
      return ResponseEntity.notFound("Resource with id " + id + " was not found");
    }

    // Modify the values of the Ordonnance object retrieved from the database
    Ordonnance ordonnanceToEdit = dbOrdonnance.get();
    ordonnanceToEdit.setField1(ordonnance.getField1());
    ordonnanceToEdit.setField2(ordonnance.getField2());
    ordonnanceToEdit.setField3(ordonnance.getField3());

    // Save to repository
    this.ordonnanceRepository.save(ordonnanceToEdit);
    return ResponseEntity.ok("Resource with ID " + id + " was successfully updated.");
}

This code should work, however you should create separate Java DTO Classes which are generally used to transfer data. This way you can only pass in the ID and the fields you would like to update, instead of having to pass in the entire object.

Upvotes: 1

Related Questions