Spring Data Rest custom controller with patch method - how to merge resource with entity

Viewed 1991

By default when we have a repository with save method exposed we can do a PATCH request. Then Spring Data REST retrieves the original object from the database and apply changes to entity and then saves it for us (inside JsonPatchHandler class). This allows us to do the following request for class

class Address {
     Long id;
     String street;
     Long houseNumber;
}

PATCH /api/addresses/1 with body

{ houseNumber: 123 }

And only this one field will be changed.

Now having custom controller we would like to in the update method receive the whole object (after HATEOAS merged it with the original object from the DB)

@RepositoryRestController
@ExposesResourceFor(Address.class)
@ResponseBody
@RequestMapping("/addresses")
public class AdddressController {

    @PatchMapping("/{addressId}")
    public Resource<Address> update(@RequestBody Resource<Address> addressResource, @PathVariable Long addressId) {
        Address address= addressResource.getContent();
        // .... some logic
        address = addressRepository.save(address);
        return new Resource<>(address);
    }
}

Unfortunately in the place where I would do some logic I get the Address with null fields instead of the merged object.

Is it possible to plug the custom controller in the Spring Data REST stack so that when patching the request it will merge it for me (as it does for normal repositories)?

edit: I would like to find a solution that works transparently both with PATCH(content-type:application/json-patch+json) and PATCH(content-type: application/hal+json)

1 Answers
Related