I have a one-to-many relationship between Part and Params (a “Part” has many “Params).
I’m trying to do something naive like this:
Part sourcePart = em.find(Part.class, partIdSource);
Part destPart = em.find(Part.class, partIdDest);
Collection<Param> paramListSource = sourcePart.getParamList();
destPart.setParamList(paramListSource);
Basically I want to copy all the parameters from sourcePart to destPart. Hopefully the persistence provider will automatically set the right foreign keys in the Param table/entity.
The above code will obviously not work.
Is there any easy way of doing this, or do I have to do create a new collection, then add each Param (creating new Param, setting attributes, etc) ?
Edit
I tried detaching the entity first like someone recommended in another thread but I get an exception (org.hibernate.PersistentObjectException: detached entity passed to persist: shared.entity.Param).
Part sourcePart = em.find(Part.class, partIdSource);
// force eager loading...
((List)sourcePart.getParamList()).get(0);
Part destPart = em.find(Part.class, partIdDest);
// detach entity
org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession();
session.evict(sourcePart);
//causes exception "detached entity passed to persist"
destPart.setParamList(sourcePart.getParamList());
If you want to go the “evict way”, making your entities Detached is NOT enough, you need to “nullify” the
Idproperties so that your entities become New again (persisting them must result in SQL INSERT). In pseudo code:But I find this dirty. I would iterate over the items of the list and use a copy constructor (without copying the
Idproperties) to create a new list and then set the copy on the destination object (and this would be provider agnostic).