spring-boot - 在做@PutMapping的时候,不初始化数据怎么添加?
问题描述
更新vue时,我设计了一个1:n关系的数据库,这样一个成员就可以拥有多个产品。但是当你更新时,之前的数据就会消失,只剩下一个新数据。我希望会员能够拥有多种产品。
--springboot(控制器)
@PutMapping(value = "/productSetting/{id}")
public ResponseEntity<User> updateUserProduct(@PathVariable("id") long id, @RequestBody Map<String, Object> data) {
Optional<User> userData = userRepository.findById(id);
Optional<ProductInfo> productInfo = productInfoRepository.findById(Long.parseLong(String.valueOf(data.get("id"))));
ProductInfo realProductInfo = productInfo.get();
if (userData.isPresent()) {
User _user = userData.get();
Set<ProductInfo> set = new HashSet<ProductInfo>();
set.add(realProductInfo);
_user.setProductInfo(set);
return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
--vue.js(脚本)
updateUserProduct() {
var data = {
id:this.currentUser.id,
productInfo: this.currentProductInfo,
};
ProductSettingDataService.update(this.currentUser.id, {id: this.currentProductInfo.id})
.then(response => {
this.currentUser = response.data;
console.log(this.currentUser);
console.log(status);
this.message = 'update Success';
})
.catch(e => {
console.log(e);
});
},
我认为这是控制器的问题,您可以就问题的哪一部分寻求帮助吗?
解决方案
Set<ProductInfo> set = new HashSet<ProductInfo>();
set.add(realProductInfo);
_user.setProductInfo(set); -- the problem is here
您正在使用一对多关系,并且当_user.setProductionInfo(Collection)
您更新整个关系时 - 集合中的所有条目都被插入\更新,并且之前属于用户且集合中不存在的所有旧条目都将被删除.
使用一对多关系使其按预期工作:
_user.getProductInfo().add(realProductInfo); // to Insert
_user.getProductInfo() // to Update
.stream()
.filter(pi -> Objects.equals(pi.getId(), data.get("id"))
.findFirst()
.ifPresent(pi -> //update ProductInfo consumer);
userRepository.save(_user);
但是你为什么不考虑更新 ProductInfo 实体而不是用户呢?
productInfoRepository.findByIdAndUserId(productInfoId, userId)
.map(//set fields UnaryOpertor)
.map(productInfoRepository::save)
.map(ProductInfo::getUser) // You may need to select user from repo, depends on entities
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
推荐阅读
- python - 在熊猫数据框中附加两列的最小值
- python - 我正在尝试为 python3.7 获取项目
- javascript - 如何使用 Lodash 根据对象的嵌套属性值选择对象的属性?
- import - 在 teraform 中,有没有办法在不使用 CLI 命令的情况下使用 TF 文件刷新资源状态?
- python - bt - Python 的灵活回测 - 如何获得每个给定日期的总投资组合价值/结果?
- javascript - reactjs如何在子组件中进行动态路由?
- parallel-processing - 暂存空间与主节点磁盘空间中的普通磁盘空间有何不同?
- python - discord.ext.commands.errors.ExtensionNotFound:无法加载扩展“cogs.random”
- c# - 默认结构的正确处理
- git - 无法使用交互式变基更改 git 提交消息