在hibernate中合并父项后获取子ID [英] Get the child id after merging the parent in hibernate

查看:125
本文介绍了在hibernate中合并父项后获取子ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何干净的方法来获得子对象的id,当父对象被合并?

I.e。

 父亲= parentDao.get(parentid); 
Child child = new Child();
parent.addChild(child);
parentDao.merge(parent);
child.getId()//为空

我之间有多对一的关系父母和孩子。



另一个问题提出了这个问题,唯一有效的解决方案是遍历儿童列表,但这听起来很可怕,很可笑。



JPA如何从父级使用合并但创建子级时获取生成的id / object?



当然,必须有一个更好的解决方案。

解决方案

考虑以下双向实体结构,即

  class Parent {
@OneToMany
List< Child>儿童;
}

class儿童{
@ManyToOne
父亲;
}

您需要先坚持孩子才能获得id

entityManager.persist(child),然后将它与父级,除非您在父类中设置了 cascadeType Cascade.ALL


Is there any clean way to get the id of a child object, when the parent has been merged?

I.e.

Parent parent = parentDao.get(parentid);
Child child = new Child();
parent.addChild(child);
parentDao.merge(parent);
child.getId() // is null

I have a many to one relationship between the parent and the child.

Another question asked this, and the only solution that worked was to traverse the list of children, but that sounds horrible and hacky.

JPA How can I get the generated id/object when using merge from parent but child is created?

Surely there must be a nicer solution to this.

解决方案

Considering the following bi-directional entity structure, i.e.

class Parent{
    @OneToMany
    List<Child> children;
}

class Child{
    @ManyToOne
    Parent parent;
}

You'll need to persist the child first in order to get the id for the child.

like entityManager.persist(child) and then associate it with the parent unless you have set cascadeType to Cascade.ALL in Parent class.

这篇关于在hibernate中合并父项后获取子ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆