gpt4 book ai didi

java - 持久化实体时设置 OneToMany 关系的 id

转载 作者:行者123 更新时间:2023-11-30 10:07:44 24 4
gpt4 key购买 nike

我有一个 hibernate 应用程序,我想在其中保留一个所有者。

一个主人可以养很多动物

(在 Owner 实体内部)

   @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 body

  {
"name": "kristoffer",
"email": "Kristofferlocktolboll@gmail.com",
"age": 23,
"animals": [{
"id": 1,
"name": "Simba",
"weight": 110,
"species": {
"id": 1,
"name": "Lion"
}
}]
}

最佳答案

你得到那个错误是因为你试图持久化一个分离的实体:动物。

解决方案

在 Owner 实体中,保持原样(尽管 CascadeType.MERGE 就足够了):

@OneToMany(cascade = CascadeType.ALL)
private List<Animal> animals;

然后,在create方法中,将persist替换为merge:

getEntityManager().merge(owner);

这样做的原因是您需要对 animals 列表进行合并操作。

关于java - 持久化实体时设置 OneToMany 关系的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54108356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com