What is the best practice for supporting HTTP PATCH in custom Spring MVC controllers? Particularly when using HATEOAS/HAL? Is there an easier way to merge objects without having to check for the presence of every single field in the request json (or writing and maintaining DTOs), ideally with automatic unmarshalling of links to resources?
I know this functionality exists in Spring Data Rest, but is it possible to leverage this for use in custom controllers?
I do not think you can use the spring-data-rest functionality here.
spring-data-rest is using json-patch library internally. Basically I think the workflow would be as follows:
I think the hard part is the fourth point. But if you do not have to have a generic solution it could be easier.
If you want to get an impression of what spring-data-rest does - look at org.springframework.data.rest.webmvc.config.JsonPatchHandler
EDIT
The patch mechanism in spring-data-rest changed significantly in the latest realeases. Most importantly it is no longer using the json-patch library and is now implementing json patch support from scratch.
I could manage to reuse the main patch functionality in a custom controller method.
The following snippet illustrates the approach based on spring-data-rest 2.6
import org.springframework.data.rest.webmvc.IncomingRequest;
import org.springframework.data.rest.webmvc.json.patch.JsonPatchPatchConverter;
import org.springframework.data.rest.webmvc.json.patch.Patch;
//...
private final ObjectMapper objectMapper;
//...
@PatchMapping(consumes = "application/json-patch+json")
public ResponseEntity<Void> patch(ServletServerHttpRequest request) {
MyEntity entityToPatch = someRepository.findOne(id)//retrieve current state of your entity/object to patch
Patch patch = convertRequestToPatch(request);
patch.apply(entityToPatch, MyEntity.class);
someRepository.save(entityToPatch);
//...
}
private Patch convertRequestToPatch(ServletServerHttpRequest request) {
try {
InputStream inputStream = new IncomingRequest(request).getBody();
return new JsonPatchPatchConverter(objectMapper).convert(objectMapper.readTree(inputStream));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With