Forums Register Login

Can I change the value of the PK (Hibernate)

+Pie Number of slices to send: Send
I have a class whose primary key is a String property. The initial value of the PK is set in a business rule. Now there is a rule to change the value of the primary key while keeping all the child records. The database constraints allow that (foreign keys with "on update cascade" option). So all I did was change the PK and save the object -- Hibernate's "update" method, but it threw an exception: Don't change the reference to a collection with cascade="all-delete-orphan": [set name]

Am I doing an invalid operation by changing the PK value, even though it remains unique, or is it Hibernate? Must I change the PK to be auto-generated as I had to do a dozen times when mapping collections?

Thanks in advance
+Pie Number of slices to send: Send
 


Am I doing an invalid operation by changing the PK value, even though it remains unique, or is it Hibernate?


A bit of both. In relational databases it is the PK that uniquely identifies data. A definition of a PK would usually be that it is unique, not null and unchanging. So conceptually if you change the PK you are not "updating" data, you are deleting and inserting it.

I know that databases will allow you to update PKs with an update statement, so normally you could do this easily enough. But Hibernate is very strict about following PK rules so if you change a PK value you change the identity of the object and so can't use any of Sessions's update methods. You would in fact have to delete the parent object and all its child objects and recreate them to do what you want to do.

If I were you, I'd add a surrogate key to your table (if you can) and change your String "key" to just have a unique constraint. This way you can change its value without any headaches.
Would you turn that thing down? I'm controlling a mind here! Look ... look at the tiny ad ...
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 6582 times.
Similar Threads
Update value of primary key impossible
Java Hibernate Cascading Issue
Get back the object
updating primary key
How does one insert a column value into an existing record?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 01:36:34.