0

I am in a very similar situation to the question here: Spring boot how to edit entity.

I have an "Item" entity for which I want to edit a number of attributes (possibly one, possibly all of them) - but the key. I have understood that BeanUtils.copyProperties(sourceItem, targetItem, "id"); is great for such cases. From the question that I linked, I have also further seen that a way of doing this edit is simply through creating an update method in the controller as follows:

@PutMapping("/{id}")
public ResponseEntity<?> update(@PathVariable("id") Item targetItem, @RequestBody Item sourceItem) {
    BeanUtils.copyProperties(sourceItem, targetItem, "id");
    return ResponseEntity.ok(repo.save(targetItem));
}

The problem that I am facing is that I have more than one path variable. Thus to edit the item, i would rather need something like @PutMapping("/{id1}/{id2}/{id3}"), since the item itself is linked to other items.

Thus what I tried doing (based on the linked question) is:

@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));
}

I think the faulty part is @PathVariable("id1/id2/id3"), since the IDE does tell me that the pathing cannot be found.

I would like to know if you can think of an elegant way of dealing with the multiple variables issue - I feel like using BeanUtils.copyProperties() is a clean way of editing something and I would enjoy keeping that intact.

1 Answer 1

0

I think you should map to 3 different path variables:

@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));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.