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

前端 未结 9 683
抹茶落季
抹茶落季 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:57

    You could clone the object and wipe the id and save it back down so a new Id is assigned.

    so

    Person person = EmployeeDAO.get(empId);
    Person newPersonCopy = person.createCopyWithNoId()
    EmployeeDAO.add(newPersonCopy);
    

    in this case the createCopyWithNoId() would create a clone of the object and set the Id field to null. when you now add the new clone the hibernate engine will see it as a new object persist it and the database will assign a new primary key.

    Please notice i avoided calling the method clone because what comes out is not an exact clone as we manipulate the Id (setting it null);

    Another way to go would be to add a constructor that took in an object of type person and created a new object but simply didn't set the Id field leaving it at its default value of null. Again you persist using the DAO.

提交回复
热议问题