我可以分享我的 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。我可以通过某种方式改进我的两个实现吗?