我有商家和地址表。一个商家可以有多个地址,一个地址有一个商家(一对多关系)。当用地址添加商家价值时,我收到此错误。如何解决此错误?这是错误。{ "timestamp": 1554878673504, "status": 500, "error": "Internal Server Error", "message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement", "path": "/merchant-service/save-merchant"}这是我的输入值: { "idNo": null, "idType": null, "emailId": "email@gmail.com", "name": null, "status": true, "createdBy": null, "modifiedBy": null, "createdDate": null, "modifiedDate": null, "contacts": [ {"contactNo": "0766601122"}], "addresses": [ {"line1": "manipay"}, {"line1": "suthumalai"} ] }这是我在商家模型中的代码: @OneToMany(fetch = FetchType.LAZY,cascade = {CascadeType.ALL}, mappedBy = "merchant") private Set<Address> addresses = new HashSet<Address>( 0);这是我在地址模型中的代码: @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "merchant_id", nullable = false)// @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})// @Getter(onMethod = @__( @JsonIgnore))// @Setter private Merchant merchant;这是我的服务:public Merchant saveMerchant(Merchant merchant) { merchant = merchantRepository.save(merchant); return merchant; }
2 回答

森栏
TA贡献1810条经验 获得超5个赞
我是你的商家模型,你为地址属性设置的。这意味着在这种情况下,如果您想保留具有某些地址的 Merchant 对象,休眠将检查这些地址是否已存在;如果没有,它将在之前创建它们。但在地址模型中,您设置为商家属性,这意味着如果没有现有商家,则无法保留地址对象。然后,当休眠者尝试持久化商家并找到尚未持久化的地址时,它会尝试在此之前持久化此地址,它还会找到一个空 Merchant 对象,然后引发此异常。cascade = {CascadeType.ALL}
nullabel = false
org.hibernate.exception.ConstraintViolationException
您必须选择以下建议之一:
删除地址模型上商家属性中的约束。如果您这样做,地址将保留在没有商家的情况下。然后,当您坚持时,商家休眠将更新地址。
nullable = false
更改为除“商家模型的 PERSIST 地址”属性之外的所有其他级联。如果您这样做,您应该在自己之前保留商家,然后将地址保留在现有商家中。
cascade = {CascadeType.ALL}

POPMUISE
TA贡献1765条经验 获得超5个赞
在“商品”表中:
@OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE}, mappedBy = "merchant") private Set<Address> addresses = new HashSet<Address>( 0);
在地址表中:
@ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "merchant_id") @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) @Getter(onMethod = @__( @JsonIgnore)) @Setter private Merchant merchant;
使用中:
public Merchant saveMerchant(Merchant merchant) { merchant = merchantRepository.save(merchant); Merchant finalMerchant = merchant; merchant.getAddresses().forEach(address -> { address.setMerchant(finalMerchant); addressRepository.save(address); }); return merchant; }
它完美地工作。
添加回答
举报
0/150
提交
取消