[英]How to add values to many side in one to many relationship spring boot
我有商家和地址表。 一個商家可以有多個地址,一個地址有一個商家(一對多關系)。當添加商家價值的地址時,我收到此錯誤。 如何解決這個錯誤? 這是錯誤。
{
"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;
}
它表示您有一個Constraint違規錯誤,這意味着您可能已將實體中的任何一個變量設置為非null,並且您嘗試保存空值。
我是您的商家模型,您為地址屬性設置了cascade = {CascadeType.ALL}
。 這意味着對於這種情況,如果你想堅持一個具有一些地址的Merchant對象, hibernate將檢查這些地址是否已經存在; 如果不是,它將在之前創建它們。 但是在您的地址模型中,您將nullabel = false
設置為商家屬性,這意味着如果沒有現有商家,則無法保留地址對象。 然后,當hibernate嘗試持久化Merchant並找到尚未持久化的Address時,它會嘗試在此之前保持此Address,它還會找到一個null Merchant對象,然后拋出此異常org.hibernate.exception.ConstraintViolationException
。
您必須選擇以下提案之一:
在地址模型上的商家屬性中刪除nullable = false
約束。 如果你這樣做,地址將在沒有商家的情況下保留。 然后當你堅持商家hibernate會更新地址。
將cascade = {CascadeType.ALL}
更改為除商家模型的地址屬性中的PERSIST之外的所有其他級聯。 如果你這樣做,你應該先堅持商人,然后堅持現有商家的地址。
在Merchent表中:
@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;
}
它完美地工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.