spring引导获取(和编辑)具有多个路径变量的实体

unftdfkk  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(367)

我的处境与这里的问题非常相似:spring boot如何编辑实体。
我有一个“item”实体,我想为它编辑一些属性(可能是一个,也可能是所有属性)——但是键。我明白了 BeanUtils.copyProperties(sourceItem, targetItem, "id"); 对这种情况很好。从我链接的问题中,我还进一步了解到,执行此编辑的方法只是通过在控制器中创建更新方法,如下所示:

@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() 是一个干净的方式编辑的东西,我会喜欢保持原封不动。

brccelvz

brccelvz1#

我认为应该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));
}

相关问题