【问题标题】:Setting id of OneToMany relationship when persisting entity持久化实体时设置 OneToMany 关系的 id
【发布时间】: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&lt;Animal&gt; animals?另外,您有某种版本控制吗?
  • @Eugen Covaci 传入的动物列表,在 JSON 正文中
  • animals 列表已存在于数据库中?
  • 是的,尤金确实如此。
  • @XtremeBaumer 我认为同样的交易是可能的..

标签: java hibernate jpa persistence


【解决方案1】:

您收到该错误是因为您试图持久化一个分离的实体:Animal。

解决方案

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

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

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

getEntityManager().merge(owner);

原因是animals 列表需要合并操作。

【讨论】:

  • 只是出于好奇,是merge,被使用,因为,它还需要merge(更新,),动物列表?
  • @baileyhaldwin 是的。
猜你喜欢
  • 2020-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-27
  • 2020-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多