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 wa
As mentioned in the comments to the accepted answer, detatch will ignore unflushed changes to the managed entity.
If you are using spring you have another option which is to use org.springframework.beans.BeanUtils
Here you have BeanUtils.copyProperties(Object source, Object target)
. This will allow you to do a shallow copy without tampering with the entityManager.
Edit: quote from api doc: "this method is intended to perform a "shallow copy" of the properties and so complex properties (for example, nested ones) will not be copied."
This blog post may inform you more about deep copying java objects.
I just tried setting the id to null and it worked
address.setId(null);
address = addrRepo.save(address);
setting the id to null made it so it saved into a new record with new id since i have it automatically generated.