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:
@Id
field to null
and persisting it will work?@Id
)?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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With