Search code examples
jpasql-updateentitymanageridentifier

Updating the ID of an instance in JPA


I am using JPA annotations(hibernate implementation), and i want to change the ID of an entity by merging it.There is any annotation or solution to avoid duplicating then removing the entity?


Solution

  • This is not possible using JPA, for good reasons:

    • you have an entity removed from the persistence context and you want to reattach it, how possibly could it be connected to the original row it was modified from if you remove the only way to make the connection? Ok, let's assume we store the original id and try to go from there, but now since id is modifiable there is 0 guarantee that it wasn't changed by some other process as well while it was detached, making our stored original id useless and causing complete chaos.

    You can do workarounds though:

    • use a native query to modify the row
    • don't use this column as your primary key but instead create a new one with generated sequences
    • duplicate then remove entity as you said is also completely valid and safe as it's in the same transaction