How to clone a JPA entity

krisy picture krisy · Jul 24, 2012 · Viewed 45.9k times · Source

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)?

Answer

SJuan76 picture SJuan76 · Jul 24, 2012

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.