Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep clone of Hibernate entity

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.

like image 830
Agustinus Verdy Avatar asked Jul 13 '13 10:07

Agustinus Verdy


People also ask

Can we achieve deep cloning of an object by serialization?

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.

Does clone make a shallow or deep copy?

clone() method of the object class support shallow copy of the object.

How do you detach an object in hibernate?

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.


1 Answers

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.

like image 53
Jayaram Avatar answered Sep 20 '22 01:09

Jayaram