0

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;

N. G.
  • 7
  • 2
  • I think this can be useful: https://stackoverflow.com/questions/38893831/spring-data-crudrepositorys-save-method-and-update – mohamad.zamani Sep 09 '22 at 14:58

1 Answers1

1

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);
}
Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
  • detach may make it unmanaged, but it can still have hooks in it that let the provider know it was a managed entity at one point, and of course versioning and auditing info within it. Spring 'save' may call persist on it, which pushes that same instance back into the context with those hooks, so while this may work in theory, I wouldn't depend on it. Better IMO to make a copy if you are going to create a new instance of the same entity data with a copy method that allows resetting the ID and any other properties and relationships that might be needed. – Chris Sep 09 '22 at 15:17