JPA从父级合并但创建子级时,如何获取生成的ID/对象? [英] JPA How can I get the generated id/object when using merge from parent but child is created?
问题描述
我有一个实体,该实体以前已经过固定,并且与另一个实体具有@OneToMany
关系.为了添加新实体,我只需在托管对象中添加新实体,然后使用cascadeType.ALL
保留更改.有什么方法可以获取新创建的对象的ID或获取我用于合并以更新其ID的原始(非托管)对象?
I have an entity that has been previously persited and has a @OneToMany
relationship with another entity. In order to add a new entity I just add my new entity in the managed object and use cascadeType.ALL
to persist the changes. Is there a way that I can get the id's of the newly created objects or get the original (unmanaged) object I used with the merge to have its id updated?
在伪代码中,我希望发生以下情况:
In pseudo-code I would expect the following to happen:
- 将为合并实体返回新副本
- 旧副本将针对新实体进行更新
示例: 父母A,id = 13 子B,id = 0
Example: Parent A, id=13 Child B, id=0
从本质上讲,我想在父级上发布merge
,但在子级上级联persist
(以便原始子级实例被更新,而不是被复制).
In essence, I want to issue a merge
on the parent but cascade persist
on child (so that the original child instance is updated, not copied).
显然这不会发生. 我正在使用休眠作为提供程序.
Obviously this doesn't happen. I am using hibernate as the provider.
推荐答案
Stackoverflow JPA文档只要您进行研究即可得到答案.
Stackoverflow post and JPA documentation have the answer provided that you do your research.
要做我要的方法是在托管父级上使用persist
.这将忽略对父级所做的任何更改,但会级联persist
(前提是已将其设置为级联).之后,子对象将具有正确的ID.
The way to do what I want is to use persist
on the managed parent. This will ignore any changes on the parent, but will cascade persist
(provided that it is set up to cascade). The child object will have the correct id afterwards.
....
JPAEntity newObject=new JPAEntity();
managedObject.addChild(newObject);
em.persist(managedObject)
newObject.getId() //work fine!
这篇关于JPA从父级合并但创建子级时,如何获取生成的ID/对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!