Nov 22nd, 2007, 06:17 AM
Deep cloning of object graph in Hibernate
We have a requirement that involves cloning of a fairly complex object graph. What we need is to take an existing graph of objects (with one root i.e. the root of the aggregate) and clone them all with new ids but at the same time maintaining the relationships between them.
Is there an easy, robust way of doing this?
I have tried implementing cloneable and calling .clone() which is fine for the root object but all the other objects in the graph are not cloned (the original objects are referenced from the clone).
I have also tried using the Hibernate utility SerializationHelper.clone() which does a better job of cloning the related objects but still they are not detached from the session. Even if you nullify their ids hibernate still does not automatically recognise that you are trying to insert new records.
I don't want to end up with a fragile nasty bit of code that breaks every time we refactor the domain model...
Any help with this would be greatly appreciated
Nov 28th, 2007, 12:13 AM
My first thought on your question was that you want a copy, not a clone, since I have a different understanding between both of them: A clone preserves all the state of an object including IDs etc. The default serialization by SerializationHelper seems to match my understanding of clone() which is different from what you want. (As mentioned serialization also has the other drawback of being much slower.)
The Javadoc for Object.clone() says though that it returns a copy of the object, but the exact meaning of "copy" is not defined but up to the implementation. So you are actually free to do it the way you want but there is no support for this non-standard way. So in your implementation of clone() you also need to clone all referenced objects. This is of course not as maintenance-friendly as the standard way.
If you don't want to confuse other readers you might want to name you method copy() instead of clone()
Nov 28th, 2007, 03:24 AM
Thanks for your reply Jörg, I have (hopefully) managed to convince the users that they actually don't need the clone/copy capability, what they actually need is an audit trail which can be implemented a lot more cleanly using other techniques.