How to clone an entity with JPA and Hibernate


#1

My scenario is to make a copy of an entity that already has id of its own and all child entities
and insert it to db.

Asset existingAsset = getAssetFromDb(assetId);
getSession().detach(existingAsset);

Asset copyAsset = copyService.copyAsset(existingAsset);
this.getSession().save(copyAsset);

and it fails due to the already defined ids that were copied from existingAsset.
If I call this.getSession().saveOrUpdate(copyAsset); it just updates existing asset with copy, but not insert new record.

Is there any good way to solve the problem?


#2

Do you copy the id? If so it’s normal it doesn’t work and complain about you using the same id twice.


#3

The problem is the @Id generator strategy you’re using there. I suppose you are using an automatic identifier strategy like IDENTITY or SEQUENCE.

Because you are copying the id as well, Hibernate will think that you want to persist a new entity, but that entity already has an identifier.

Just make sure you skip the id in the cloned entity and leave it null. This way, Hibernate will see that you passed a transient entity and will persist it for you.

Since this question is a very good one, I also wrote an article about the best way to clone or duplicate an entity with JPA and Hibernate.