• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can I change the value of the PK (Hibernate)

 
Henrique Sousa
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic