Hibernate INSERT then DELETE, why does it do this in this order?
Kevin P Smith
posted 3 years ago
Just a quick question (there might be an obvious answer).
Why does Hibernate perform INSERTs then DELETEs when executing a transaction?
I ask this, because we are having an issue where we have a List of items with a unique reference, when a user tries to remove on item from that list and replace it with a new one, we are getting an MySQL level error about a non-unique reference. This seems to be happening (from what I've read on a few sites) because Hibernate performs INSERTs forst, then UPDATEs then DELETEs.
So at the point of INSERT it would make sense that MySQL is trowing the error, but it doesn't make sense to me that hibernate works in this way.
Why does Hibernate do this and is there a way we can reverese this to DELETE then INSERT, or do we have to create two seperate transactions.
This is considered a feature. Hibernate does things in a special order to prevent foreign-key constraints from being violated. There is no way to reverse this general rule however you can override the behavior in any instance by calling flush after your deletes but before your inserts. In this case the deletes will be executed first.