Spring Rest Controller Patch实现

时间:2017-05-21 19:30:22

标签: spring spring-mvc jackson patch spring-restcontroller

我需要在我的Spring [{1}}上实现PATCH功能。

我看到了很多问题,最常见的方法是使用普通的Java @RestController来执行此操作。允许Map的映射有助于解决null或缺少值的问题,因为它似乎无法在POJO上实现。

Spring是否有开箱即用的功能,有助于将Map中的值反映到现有模型对象,或者我必须自己实现它...例如使用Jackson等等?

1 个答案:

答案 0 :(得分:1)

我可以分享我的PATCH实现,希望这能以某种方式帮助一些人。我有一个客户端有六个字段,如(名称,类型,地址字段,ID,数字,邮政编码),我可以编辑客户端并更改任何内容。

这也是对部分答案的问题的详细阐述(如果除了以下两种情况之外没有其他办法,那么也是一个完整的答案)或者也许PATCH应该以不同的方式完成

clientService只是一个包含ClientRepository

的服务
 @RequestMapping(value = "/{id}", method = RequestMethod.PATCH ,produces = {"application/vnd.api+json"} )
    ResponseEntity<Resource<Client>> editClient(@PathVariable("id") Integer id,@RequestBody Client editedClientFromBrowser) {
// the id is the ID of the client that I was editing.. 
 //i can use this to retrieve the one from back end
// editedClientFromBrowser is the changed Client Model Object 
//from the browser The only field changed is the one
//  that was changed in the browser but the rest of 
//the object is the same with the ID as well

        logger.info("Edit Client reached");

     //retreive the same Client from backend and update and save it
    //    Client client = clientService.getClient(id);
    //    if (client == null) {
    //        throw new EntityNotFoundException("Client not found - id: " + id);
    //    }else{
    //      change the field that is different from the 
    //editedClientFromBrowser and then saveAndFlush client
    //}

    //OR saveAndFlush the editedClientFromBrowser itself
    clientService.saveAndFlush(editedClientFromBrowser);
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);


    }

现在我读了另一种方法(http://www.baeldung.com/http-put-patch-difference-spring)并尝试了:

 @RequestMapping(value = "/{id}", method = RequestMethod.PATCH ,
   produces = {"application/vnd.api+json"}  )
    ResponseEntity<Resource<Client>> editClient(@PathVariable("id") Integer id, 
     @RequestBody Map<String, Object> updates) 

这个确实给了我一个hashMap。但它给了我每一个领域。即便是那些我没有改变的。那么,这真的有益吗?不明白,可能比获得整个客户端对象更轻。

如果我只获得一个或两个字段的hashmap,我会更喜欢。我认为这可能更符合PATCH。我能以某种方式改进我的两个实现吗?