How to deep copy a Hibernate entity while using a newly generated entity identifier

Just retrieve the object, detach it, set the id to null and persist it.

MyEntity clone = entityManager.find(MyEntity.class, ID);
entityManager.detach(clone);
clone.setId(null);
entityManager.persist(clone);

If your object have oneToMany relationships, you will have to repeat the operation for all the children but setting your parent object id (generated after the persist call) instead of null.

Of course you will have to remove any CASCADE persist on your OneToMany relationships cause otherwise your persist will create duplicates of all children in DB or fk constraint failures.

Leave a Comment