tags:

views:

39

answers:

2

What I have is an entity bean e.g. 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 e.g. 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

A: 

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.

Bozho
+1  A: 

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

i.e.

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.

James