0

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");
}
Kindth
  • 337
  • 1
  • 8
  • 30

1 Answers1

1

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.

Brice Frisco
  • 409
  • 1
  • 4
  • 15
  • I did that before if(ordonnance.getField1()!=null) then I set the field ordonnanceToEdit.setField1(ordonnance.getField1()); because if I remove if I got other fields null when I update some of them I don't know if its a wise code or no – Kindth May 21 '20 at 00:51
  • This is good but it will only work when the existing fields are to be edited, we can't add a new field with this approach. – Parag Kadam May 27 '21 at 13:37
  • Pulling the record from the DB simply to use setters seems like a waste of a DB connection. – Half_Duplex Mar 01 '22 at 23:41