【发布时间】:2019-01-09 10:46:54
【问题描述】:
我有一个休眠应用程序,我想在其中保留一个所有者。
一个主人可以养很多动物
(内部所有者实体)
@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
所以我考虑使用一种级联,以确保动物将 Owner 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"
}
}]
}
【问题讨论】:
-
如何构建提供给
create方法的List<Animal> animals?另外,您有某种版本控制吗? -
@Eugen Covaci 传入的动物列表,在 JSON 正文中
-
animals列表已存在于数据库中? -
是的,尤金确实如此。
-
@XtremeBaumer 我认为同样的交易是可能的..
标签: java hibernate jpa persistence