Cloning JPA entity

前端 未结 8 1437
闹比i
闹比i 2020-11-29 01:55

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

相关标签:
8条回答
  • 2020-11-29 02:39

    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.

    0 讨论(0)
  • 2020-11-29 02:43

    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.

    0 讨论(0)
提交回复
热议问题