Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone a JPA entity

I have a JPA entity already persisted in the database.
I would like to have a copy of it (with a different id), with some fields modified.

What is the easiest way to do this? Like:

  • setting it's @Id field to null and persisting it will work?
  • will I have to create a clone method for the entity (copying all fields except the @Id)?
  • is there any other approach (like using a cloning framework)?
like image 805
krisy Avatar asked Jul 24 '12 06:07

krisy


2 Answers

Use EntityManager.detach. It makes the bean no longer linked to the EntityManager. Then set the Id to the new Id (or null if automatic), change the fields that you need and persist.

like image 156
SJuan76 Avatar answered Sep 25 '22 13:09

SJuan76


When using EclipseLink, you can use the VERY handy CopyGroup-Feature:

http://wiki.eclipse.org/EclipseLink/Examples/JPA/AttributeGroup#CopyGroup

A big plus is that without much fiddling it properly clones private-owned relation-ships, too.

This is my code, cloning a Playlist with its private-owned @OneToMany-relationship is a matter of a few lines:

public Playlist cloneEntity( EntityManager em ) {     CopyGroup group = new CopyGroup();     group.setShouldResetPrimaryKey( true );     Playlist copy = (Playlist)em.unwrap( JpaEntityManager.class ).copy( this, group );     return copy; } 

Make sure that you use persist() to save this new object, merge() does not work.

like image 40
schieferstapel Avatar answered Sep 23 '22 13:09

schieferstapel