Spring Data Rest user controller with patch method - how to combine a resource with an entity

By default, when we have a repository with an open save method, we can execute the PATCH request. Then, Spring Data REST fetches the source object from the database and applies the changes to the entity, and then saves it for us (inside the JsonPatchHandler class). This allows us to execute the following query for the 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 that we have a custom controller, we would like the whole object to be retrieved in the update method (after HATEOAS combined it with the original object from the database)

 @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 an address with zero fields instead of a merged object.

Is it possible to connect a user controller in the Spring Data REST data stack so that when a request is corrected, it combines it for me (as well as for regular repositories)?

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

+5
source share
1 answer

After looking at the Spring sources, I did not find a reasonable solution. As a result, I created a problem in their JIRA

At the moment there is only one reasonable solution - create a user controller with the PersitentEntityResource parameter and have both {id} and {repository} placeholders in its path ie

 @PatchMapping("/addresses/{id}/{repository}") public Resource<Address> update(PersistentEntityResource addressResource) { ... } 

which makes the endpoint of the call / address / 123 / address

0
source

Source: https://habr.com/ru/post/1268399/


All Articles