我正在将 Spring Boot 与 Spring Data JPA 和 Postgre 一起使用。我有“项目”实体,其中包含价格、数量、自动生成的 int id 和它所属的订单。 我搜索了如何编辑该实体,仅更改其价格和数量,而不创建新实体,我得到的唯一答案是从数据库获取实体并将每个属性设置为新属性,然后保存它。但是,如果我除了价格和数量之外还有 6 个其他属性,这意味着在更新方法中我将设置一个属性 8 次,在我看来,这对于 spring 来说似乎是太多的样板代码。我的问题是:有更好/默认的方法吗?
最佳答案
您可以提供 copy constructor :
public Item(Item item) {
this(item.price, item.quantity);
}
或使用org.springframework.beans.BeanUtils
方法:
BeanUtils.copyProperties(sourceItem, targetItem, "id");
然后在 Controller 中:
@RestController
@RequestMapping("/items")
public class ItemController {
@Autoware
private ItemRepo repo;
@PutMapping("/{id}")
public ResponseEntity<?> update(@PathVariable("id") Item targetItem, @RequestBody Item sourceItem) {
BeanUtils.copyProperties(sourceItem, targetItem, "id");
return ResponseEntity.ok(repo.save(targetItem));
}
}
关于java - Spring Boot如何编辑实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904389/