0

I have a requirement to implement an HTTP PATCH method in a Spring MVC application. I followed this tutorial: https://www.baeldung.com/http-put-patch-difference-spring.

This is the piece of code:

@RequestMapping(value = "/heavyresource/{id}", method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> partialUpdateGeneric(
  @RequestBody Map<String, Object> updates,
  @PathVariable("id") String id) {

    heavyResourceRepository.save(updates, id);
    return ResponseEntity.ok("resource updated");
}

The problem is that my repository (JPARepository) does not have a method "save" where I can pass a map and an id.

I tried this implementation on my own:

@PatchMapping("/heavyresource/{id}")
public Beer patchUpdate(@RequestBody HeavyResource heavyResource) {

    return heavyResourceRepository.save(heavyResource);
}

But it does not work properly because if I pass only one property (that's the point in PATCH) it let's all the others properties as null and I need to update only the property that was passed. Even thinking in DTOs I was not able to implement.

Thanks!

Renan Geraldo
  • 605
  • 1
  • 6
  • 17
  • The article referred to is a bit of a joke as it doesn't (other than in passing) cover the the scenario you mentioned. You need to deal with handling nulls yourself. See my previous answer here for further info: https://stackoverflow.com/a/39424421/1356423 If the you use the Spring Data Rest extension then Patch is supported as per your requirements. – Alan Hay Jun 04 '19 at 07:14
  • I've put together some details on how to use `PATCH` in this [post](https://cassiomolin.com/using-http-patch-in-spring/). And the approach described in the post was used in this [example](https://github.com/cassiomolin/http-patch-spring) available on GitHub. – cassiomolin Jul 30 '19 at 22:34

0 Answers0