How to deep copy a Hibernate entity while using a newly generated entity identifier

前端 未结 9 675
抹茶落季
抹茶落季 2020-12-30 20:05

I\'m using a relational DB using a single column pk with a few nested tables.

I need to add a simple archiving to my project. The archiving only happens when the appl

9条回答
  •  臣服心动
    2020-12-30 20:40

    We had got similar requirement, in which we need to copy entity at certain point of transaction and use it for Audit. Solution is pretty simple. We can use Json Object Mapper.

    public class Employee {
       public int id;
       public String name;
    }
    
    Employee employee = entityManager.find(Employee.class, ID); 
    
    ObjectMapper mapper = new ObjectMapper();
    Employee deepCopiedEmployee = mapper.readValue( mapper.writeValueAsString( employee ), Employee.class );
    deepCopiedEmployee.setId(null);
    

    Another option is to use In-house Spring Utils.

    org.springframework.beans.BeanUtils.copyProperties(, , ...ignoredPropertied)
    
    Employee copiedEmployee = new Employee();
    BeanUtils.copyProperties(employee, copiedEmployee, id)
    

    Note: When using BeanUtils, Bean will be tracked in transaction. i.e. if any changes done is source bean during transaction will be reflected in target copied bean.

提交回复
热议问题