Custom Spring MVC HTTP Patch requests with Spring Data Rest functionality

。_饼干妹妹 提交于 2019-11-30 21:00:00

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:

  • read your entity
  • convert it to json using the objectMapper
  • apply the patch (here you need json-patch) (I think your controller should take a list of JsonPatchOperation as input)
  • merge the patched json into your entity

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);
          }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!