Deep copy EJB Entity beans with relationships

I have a bean object, for example. Entity (EJB 3), which stores child records of the same type in ArrayList<Entity> , its parent <Entity> and relationship to another <Users> object. Users can own many entities and vice versa (many - many).

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

I created a clone method to create an Entity clone (the new Entity that is), and then populate it with clones of children objects in the foreach loop.

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

My question is:

This is what I want to do at all, or I need to manage deep copying, for example. Facade? If possible, can you direct me to something to read or give me a couple of tips, because so far I am doing cloning through the facade, and this has become the main load in my application.

Thanks at Advance !!

pataroulis

+1
java orm jpa
source share
3 answers

Try using (from commons-lang )

 YourEntity clone = SerializationUtils.clone(entity); 

You would need to make your entities Serializable (which you might not necessarily want). This should also be done while the EntityManager is still open, otherwise you will get a lazy initialization exception.

+2
source share

You need to create a new list, otherwise you add the same list that you iterate, therefore, the exception of parallel modification.

i.e.

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

If you use EclipseLink, you can also use the copy () API in the EclipseLink JpaEntityManager. You can pass CopyGroup, which determines how deeply to make a copy, and if Id should be reset.

+1
source share

You need to deal with several issues if Oyur entities do not separate. In addition, you must clone or serialize your objects outside of the transaction, otherwise you will get a DetachedEntityPassedToPersistException (). Here is a more detailed answer :.

0
source share

All Articles