Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control order of updates in hibernate

I have a table with a unique column, "token", enforced by a unique constraint in the database. In a certain case, I need to change an existing row to have the same token as another existing row, changing the 2nd row to have a new value.

So, say I have:

id;token 0;'aaa' 1;'bbb'

I want id 0 ('aaa') to instead have the token 'bbb'. So I need to change 'bbb' to be 'jfeisefjse', and then I can change 'aaa' to be 'bbb'. This can be done in postgres in a single tranasction.

I've tried to do the same thing in code: In one transaction I get the token from the existing row (row 1), I set it to be a random value, I update the other row (row 0) to have row 1's token, then I commit. However hibernate doesn't respect the order I've done the commits in. It seems to always run the update statement for row 0 first, and postgres complains that it's violating a foreign key constraint.

How can I make hibernate do this? Either force a certain order of update statements, or some other way to do this?

Note: Doing this in two transactions (one for scrambling row 1, then another transaction to update row 0) is not an option.

like image 407
John Smith Avatar asked May 29 '11 01:05

John Smith


1 Answers

Session.flush() will force hibernate to write any pending SQL without committing the transaction. It's a bit clunky but sometimes you do need to get a little less 'ORM' and make things just work :)

like image 126
Affe Avatar answered Sep 29 '22 09:09

Affe