Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep Copy in JPA

Tags:

java

jpa

I would like to make a deep copy of an entity in JPA. I found an interesting discussion here: http://forums.java.net/jive/thread.jspa?messageID=253092&tstart=0

It sounded like the proposed solution was to set all @Id's to zero. Here's my basic code:


//Start a JPA session.
EntityManager em= emf.createEntityManager();
em.getTransaction().begin();

//Get the object I want to copy.
MyClass myObject=em.find(MyClass.class,id);

//Use reflection to find @Id's and set them to zero for all @OneToMany and @OneToOne relations.
//TODO:  write the ugly recursive code to do this.

//Hoping this will create a deep copy.
em.merge(myObject);

//Close the session.
em.getTransaction().commit();
em.close();

Is this a good strategy? Might anyone have this TODO code already written that they can share???

Thanks!

like image 563
User1 Avatar asked Jul 09 '09 21:07

User1


People also ask

What is a deep copy?

A deep copy of an object is a copy whose properties do not share the same references (point to the same underlying values) as those of the source object from which the copy was made.

What is deep copy with example?

A deep copy creates a new object and recursively adds the copies of nested objects present in the original elements. Let's continue with example 2. However, we are going to create deep copy using deepcopy() function present in copy module.

What is deep copy in Java?

Whenever you try to create a copy of an object, in the deep copy all fields of the original objects are copied exactly, in addition to this, if it contains any objects as fields then copy of those is also created (using the clone() method).

Does clone () make a deep copy?

clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.


1 Answers

I SOLVED THIS.

I created a component that makes this whole process for you based on the annotations of the package (javax.persistence).

Component already sets the id of the entity to null. He does all the analysis of the algorithm to be applied based on the type of each attribute relationship @OneToMany, @OneToOne or @ManyToMany.

Example

Person person = personDAO.find(1);
PersistenceCloner cloner = new PersistenceCloner(person); 
Person personCopy = cloner.generateCopyToPersist();

Download JAR and SOURCES: jpa-entitycloner

like image 133
Victor Lindberg Avatar answered Oct 05 '22 05:10

Victor Lindberg