[英]Spring boot getting (and editing) an entity with multiple path variables
我的情況與這里的問題非常相似: Spring boot how to edit entity 。
我有一個“項目”實體,我想為其編輯許多屬性(可能是一個,也可能是所有屬性)——但關鍵是。 我知道BeanUtils.copyProperties(sourceItem, targetItem, "id");
非常適合這種情況。 從我鏈接的問題中,我還進一步看到進行此編輯的一種方法是簡單地通過在 controller 中創建更新方法,如下所示:
@PutMapping("/{id}")
public ResponseEntity<?> update(@PathVariable("id") Item targetItem, @RequestBody Item sourceItem) {
BeanUtils.copyProperties(sourceItem, targetItem, "id");
return ResponseEntity.ok(repo.save(targetItem));
}
我面臨的問題是我有多個路徑變量。 因此,要編輯項目,我寧願需要@PutMapping("/{id1}/{id2}/{id3}")
之類的東西,因為項目本身鏈接到其他項目。
因此,我嘗試做的(基於鏈接的問題)是:
@PutMapping("/{id1}/{id2}/{id3}")
public ResponseEntity<?> update(@PathVariable("id1/id2/id3") Item targetItem, @RequestBody Item sourceItem) {
BeanUtils.copyProperties(sourceItem, targetItem, "id3");
return ResponseEntity.ok(repo.save(targetItem));
}
我認為故障部分是@PathVariable("id1/id2/id3")
,因為 IDE 確實告訴我找不到路徑。
我想知道您是否可以想出一種處理多變量問題的優雅方式——我覺得使用BeanUtils.copyProperties()
是一種編輯內容的干凈方式,我會喜歡保持原樣。
我認為您應該將 map 設置為 3 個不同的路徑變量:
@PutMapping("/{id1}/{id2}/{id3}")
public ResponseEntity<?> update(@PathVariable("id1") Item targetItem1
@PathVariable("id2") Item targetItem2, @PathVariable("id3") Item targetItem3, @RequestBody Item sourceItem) {
BeanUtils.copyProperties(sourceItem, targetItem1, "id");
return ResponseEntity.ok(repo.save(targetItem1));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.