I am wondering how can I create a deep copy of a persisted object with all of its association. Let say I have the following model.
class Document {
String title;
String content;
Person owner;
Set<Citation> citations;
}
class Person {
String name;
Set<Document> documents;
}
class Citation {
String title;
Date date;
Set<Document> documents;
}
I have a scenario in which a user might want to grab a copy of a particular document from a person and make the document his/hers then later he / she can change its content and name. In that case I can think of one way to implement that kind of scenario which is creating a deep copy of that document (with its associations).
Or maybe if anyone knows of any other possible way to do such thing without doing huge copy of data because I know it may be bad for the app performance.
I was also thinking of may be creating a reference of to the original document like having an attribute originalDocument
but that way I won't be able to know which attribute (or maybe association) has been changed.
So similar to the above cloning approaches, we can achieve deep cloning functionality using object serialization and deserialization as well, and with this approach, we do not have worry about or write code for deep cloning — we get it by default.
clone() method of the object class support shallow copy of the object.
You can detach an entity by calling Session. evict() . Other options are create a defensive copy of your entity before translation of values, or use a DTO instead of the entity in that code.
To perform a deep copy :
public static <T> T clone(Class<T> clazz, T dtls) {
T clonedObject = (T) SerializationHelper.clone((Serializable) dtls);
return clonedObject;
}
This utility method will give a deep copy of the entity, and you can perform your desired things what you want to do with the cloned object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With