Hibernate throws unique constraint violation exception while updating field part of unique key

Cshah picture Cshah · Aug 19, 2010 · Viewed 14.9k times · Source

Below is the use case: I have a unique index defined on 3 columns say A,B,C. Assume the values in them are A1,B1,C1. My java code is adding a new record say A1,B1,C1 but before this record is added, i update the previous value from C1 to C2. While trying to add the new record (after the update), hibernate is throwing an unique constraint violation exception. Any reason as to why it does? All the above statements are executed within the same transaction. My assumption is the insert happens before the update and hence the reason for the exception.

Any thoughts/suggestions ?

Answer

Pascal Thivent picture Pascal Thivent · Aug 20, 2010

My java code is adding a new record say A1,B1,C1 but before this record is added, i update the previous value from C1 to C2. While trying to add the new record (after the update), hibernate is throwing an unique constraint violation exception. Any reason as to why it does? All the above statements are executed within the same transaction.

That's how Hibernate behaves by design, it will insert the values at save() time (A1, B1, C1) and then update them (C1 to C2), it won't insert A1, B1, C2). Quoting the King in Insert and Update in same flush:

Expected Hibernate behavior (we have debated whether this is really correct or not!) is that the INSERT statement will insert exactly the data that was set when save() was called. This gives the user a bit finer grained control, especially in a context where there are triggers etc. However, if you are not careful, it could perform badly.

Suggestion: delay the save to insert (A1, B1, C2) directly.