Cloning JPA entity

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

    You could use mapping frameworks like Orika. http://orika-mapper.github.io/orika-docs/ Orika is a Java bean mapping framework that recursively copies data from one object to another. It is easy to configure and provides various flexibilities as well.

    Here is how I have used it in my project: added a dependecy :

     
          ma.glasnost.orika
          orika-core
          1.4.6
    
    

    Then use it in the code as follows:

    MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
    MapperFacade mapper=mapperFactory.getMapperFacade();
    User mappedUser = mapper.map(oldUser, User.class);
    

    This might help if you have many usecases where such kind of cloning is needed.

提交回复
热议问题