【问题标题】:Spring Rest Controller Patch implementationSpring Rest Controller 补丁实现
【发布时间】:2017-05-21 19:30:21
【问题描述】:

我需要在我的 Spring @RestController 中实现 PATCH 功能。

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

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

【问题讨论】:

  • 我整理了一个 post,描述了在 Spring 中使用 PATCH 的方法。 GitHub 上提供了一个工作示例。

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


【解决方案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。但它给了我每一个领域。即使是我没有改变的那些。那么,这真的有用吗?真的不知道,可能比取回整个客户端对象更轻松。

如果我只获得我确实更改过的一两个字段的哈希图,我会很高兴的。我认为那会更符合 PATCH。我可以通过某种方式改进我的两个实现吗?

【讨论】:

  • 你是什么意思它给你所有的领域?这取决于客户端,他必须创建一个 json(又名 hashmap)忽略尚未设置的字段,所以你只会得到要更改的字段。
猜你喜欢
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
相关资源
最近更新 更多