Save new entity after removing ID

Viewed 27

After the get action, we get the existing entity. After setting id to null, why is not created a new entity after saving action

Class A
....

A a = aRepository.findById(id);
a.setId(null);
A copiedA = aRepository.save(a);

copiedA is not a new entity. Both have the same id;

1 Answers

The entity is still managed when you call save, whether you change the ID or not.

Depending on the primary key generation strategy you would even get an exception when changing the id.

If you want to create a new entity you would need to call EntityManager.detach() before save.

Example:

Optional<Employee> employee = employeeRepository.findById(1);
if (employee.isPresent()) {
    Employee employee1 = employee.get();
    employee1.setId(null);

    // Remove the entity from the persistence context
    em.detach(employee1);

    employeeRepository.saveAndFlush(employee1);
}
Related