Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
209 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...