简体   繁体   中英

Deep copying of EJB Entity beans with relations

What I have is an entity bean eg Entity (EJB 3) that keeps same type children in an ArrayList<Entity> , his parent <Entity> and a relation to another entity <Users> . Users can own many Entities, and vice-versa (many to many).

What I would like to do is override Entity.clone() (or have a new method) to deep-copy Entity along with clones of children , belonging to the same parent and being assigned to the already existing users.

I have set up the clone method to create a clone of the Entity (a new Entity that is), and then fill it with clones of the children entities within a foreach loop.

But this gives me a concurrent modification exception and I end up with just a clone of the initial Entity bean without its children .

My question is:

Is what I want to do feasible at all or should I manage deep copying from eg a Facade? If it is feasible, could you direct me please to something to read or give me a couple of hints, because up to now I do the cloning via a facade and it has become a major burden in my application.

Thanks in Advance!!

pataroulis

Try using (from commons-lang )

YourEntity clone = SerializationUtils.clone(entity);

You would have to make your entities Serializable (which you might not necessarily want, though). Also this should be done while the EntityManager is still open, otherwise you'd get lazy initialization exception.

You have to create a new List, otherwise you are adding to the same List you are iterating over, hence the concurrent modification exception.

ie

Entity clone = super.clone();
clone.setChildren(new ArrayList());
for (Child child : this.getChildren()) {
  clone.addChild(child.clone());
}
return clone;

If you are using EclipseLink your could also use the copy() API on the EclipseLink JpaEntityManager. You can pass a CopyGroup that specifies how deep to make the copy, and if the Id should be reset.

You have to deal with several problems if oyur entities are not detached. Also you have to clone or serilize your entities outside of transaction scoper otherwithe you'll Get DetachedEntityPassedToPersistException(). Here is more elaborated answer: .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM