Copy child collection to another object

I have a one-to-many relationship between Part and Params (“Part” has many “Params”).

I am 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 correct foreign keys in the Param table / entity.

The above code will obviously not work.

Is there any easy way to do this, or do I need to create a new collection and then add each Param parameter (creating new Param parameters, setting attributes, etc.)?

Edit

, -, , (org.hibernate.PersistentObjectException: , 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());
+3
3

sourcePart destPart. , / Param.

" ", "" , " " Id, ( SQL INSERT). :

MyObject ob = session.get(idOfExisting);
hibernate.evict(ob);
ob.setId(null);
hibernate.save(ob);

. ( Id), , ( ).

+2

, clone() . paramListSource.clone().

+1

I am sure that what you get is not the actual Param instances, but proxies that implement the Param interface, so you may have to create new Param objects and copy the properties. Also, do not disconnect them from the session, since if they are proxies, they will not be able to retrieve other properties next to the identifier, which is the only one populated initially (lazy extraction).

+1
source

Source: https://habr.com/ru/post/1748469/


All Articles