Cloning JPA entity

前端 未结 8 1562
闹比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:33

    I face the same problem today : I have an entity in database and I want to :

    • get it from database
    • change one of its attributes value
    • create a clone of it
    • modify just some few attributes of the clone
    • persist clone in database

    I succeed in doing following steps :

    @PersistenceContext(unitName = "...")
    private EntityManager entityManager;
    
    public void findUpdateCloneAndModify(int myEntityId) {
      // retrieve entity from database
      MyEntity myEntity = entityManager.find(MyEntity.class, myEntityId);
      // modify the entity
      myEntity.setAnAttribute(newValue);
      // update modification in database
      myEntity = entityManager.merge(myEntity);
      // detach entity to use it as a new entity (clone)
      entityManager.detach(myEntity);
      myEntity.setId(0);
      // modify detached entity
      myEntity.setAnotherAttribute(otherValue);
      // persist modified clone in database
      myEntity = entityManager.merge(myEntity);
    }
    

    Remark : last step (clone persistence) does not work if I use 'persist' instead of 'merge', even if I note in debug mode that clone id has been changed after 'persist' command !

    The problem I still face is that my first entity has not been modified before I detach it.

提交回复
热议问题