[英]Setting id of OneToMany relationship when persisting entity
我有一個休眠應用程序,我想在其中保留一個所有者。
一個主人可以養很多動物
(內部所有者實體)
@OneToMany(mappedBy = "owner")
private List<Animal> animals;
(在動物實體內)
@ManyToOne
private Owner owner;
我有一個存儲庫,我堅持我的所有者,
@Override
public Owner create(String name, String email, int age,
List<Animal> animals) {
Owner owner = new Owner(name, email, age, animals);
for(Animal animal: animals){
animal.setOwner(owner);
}
getEntityManager().persist(owner);
return owner;
}
}
所有者正確保留,但外鍵未在動物表中設置。
我使用調試器檢查所有者是否為它的動物正確設置。
首先,我嘗試堅持導致錯誤的動物
for(Animal animal: animals){
animal.setOwner(owner);
getEntityManager().persist(animal)
} //caused an error
所以我考慮使用一種級聯,以確保動物將所有者 ID 放入數據庫中,
@OneToMany(cascade = CascadeType.ALL)
private List<Animal> animals;
這也導致了錯誤
"cause": {
"detailMessage": "detached entity passed to persist: com.tolboll.zoo.data.entities.Animal",
"stackTrace": [],
"suppressedExceptions": []
},
我怎樣才能做到這一點,所有者正確地堅持到動物實體中?
編輯:
這是傳入的 JSON 正文
{
"name": "kristoffer",
"email": "Kristofferlocktolboll@gmail.com",
"age": 23,
"animals": [{
"id": 1,
"name": "Simba",
"weight": 110,
"species": {
"id": 1,
"name": "Lion"
}
}]
}
您收到該錯誤是因為您試圖保留一個分離的實體:Animal。
解決方案
在 Owner 實體中,保持原樣(盡管CascadeType.MERGE
就足夠了):
@OneToMany(cascade = CascadeType.ALL)
private List<Animal> animals;
然后,在create
方法中,將persist
替換為merge
:
getEntityManager().merge(owner);
原因是animals
列表所需的合並操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.