简体   繁体   中英

how to update fields of primary key using hibernate

I need to update some fields of a primary key of table in some instances when using spring data jpa.Im using save method of the jpa repository to persist the changes, when changed columns include part of the primary key it gives an exception.

i'm currently getting following exception when the updated files include a column from primary key .

org.springframework.orm.ObjectOptimisticLockingFailureException

is there a way to safely update the primary key fields.

If pk is changed, what happens with foreign, you need replicate this change on children tables? Anyway, if you need to change pk values inside hibernate you must add one id column unique, mapping this as property id instead of real pk without change the real pk. But never change pk is a good idea.

Forget about modifying the value of a primary key. Just because each modification also implies modifying foreign key values.

But there is way to fix this situation:

  • Convert the current primary key into a unique key.
  • Add a numeric or uuid column, containing a generated, technical (ie non-business) primary key.
  • Unfortunately you have to update all dependents table (schema and values) so that they point to new primary key. But this has to be done once, when the database is offline.

This way it should be transparent to the other application querying the table, its query won't change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM