Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround for Spring/Hibernate due to non-standard behaviour of UNIQUE constraint in MS SQL

There is a UNIQUE database constraint on an index which doesn't allow more than one record having identical columns.

There is a piece of code, managed by Hibernate (v2.1.8), doing two DAO
getHibernateTemplate().save( theObject )
calls which results two records entered into the table mentioned above.

If this code is executed without transactions, it results INSERT, UPDATE, then another INSERT and another UPDATE SQL statements and works fine. Apparently, the sequence is to insert the record containing DB NULL first, and then update it with the proper data.

If this code is executed under Spring (v2.0.5) wrapped in a single Spring transaction, it results two INSERTS, followed by immediate exception due to UNIQUE constraint mentioned above.

This problem only manifests itself on MS SQL due to its incompatibility with ANSI SQL. It works fine on MySQL and Oracle. Unfortunately, our solution is cross-platform and must support all databases.

Having this stack of technologies, what would be your preferred workaround for given problem?

like image 850
mindas Avatar asked Dec 09 '25 13:12

mindas


1 Answers

You could try flushing the hibernate session in between the two saves. This may force Hibernate to perform the first update before the second insert.

Also, when you say that hibernate is inserting NULL with the insert, do you mean every column is NULL, or just the ID column?

like image 91
skaffman Avatar answered Dec 11 '25 01:12

skaffman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!