首页 > 解决方案 > 在做@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);
    });
},

我认为这是控制器的问题,您可以就问题的哪一部分寻求帮助吗?

标签: spring-bootvue.js

解决方案


    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());

推荐阅读