Friday, July 22, 2011

Incorrect Order of SQL execution within a Spring Hibernate Transaction

Recently I faced a strange issue when trying to insert proper data into table ,it was halting with Unique key Constraint Exception.In a transaction I had to read a record and update the Unique Key fields and in the next step insert a record .The record inserted should have the same Unique Key values as the record read from the table.The sequence was a simple read,update and insert a new record.Was baffled when this sequence continuous threw a Unique Key Constraint.When I removed the UK constraint from the table,the records were updated and inserted as required.

On checking on the hibernate log found that the insert was fired before the update .I tried to disable the Spring transaction and then the order of execution was correct.
Looks like the order of SQl execution is not guaranteed within a transaction.To solve this issue one of the following needs to be done after the update and before the insert
1.call hibernateTemplate.flush() or
2.call hibernateTemplate.refresh() or
3.again read the record from table ,this internally calls the flush.