Spring Boot如何编辑实体 [英] Spring boot how to edit entity
问题描述
我正在将spring boot与spring数据jpa和postgre一起使用.我有一个项目"实体,该实体具有价格,数量,自动生成的int id和它所属的订单.我已经搜索了如何编辑该实体,而仅更改其价格和数量,而没有创建新实体,而我得到的唯一答案是从db中获取该实体并将每个属性设置为新属性,然后保存它.但是,如果我除了价格和数量外还有其他6个属性,这意味着在更新方法中我将设置8次属性,在我看来,这似乎对spring而言是太多样板代码.我的问题是:是否有更好/默认的方法来做到这一点?
I am using spring boot with spring data jpa and postgre. I have "item" entity that has price, quantity, auto generated int id and order that it belongs to. I've searched how to edit that entity changing its price and quantity only, without making new entity and the only answer I got is to get the entity from the db and set each property to the new one then save it. But if i have 6 other properties except price and quantity that means in the update method i will set a property 8 times and this seems to me like way too much boilerplate code for spring. My question is: Is there better/default way to do that?
推荐答案
您可以提供或使用 org.springframework.beans.BeanUtils
方法:
BeanUtils.copyProperties(sourceItem, targetItem, "id");
然后进入控制器:
@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));
}
}
这篇关于Spring Boot如何编辑实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!