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:
New copy is going to be returned for merged entity
Old copy is going to be update for new entities
Example:
Parent A, id=13
Child B, id=0
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 post and JPA documentation have the answer provided that you do your research.
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!