I came across this false “Duplicate entry” problem because mysql is checking on each sql statement the unique constraints. More over, I do not seem to find a well documentation solution somewhere.
The problem: With hibernate+mysql, we want to modify an entire collection (using insert/update instead od deleteAll/insertAll), then even though your new collections is compliant with the unique constraint, you can get ‘Duplicate entry’ since each time one entity of the collection is insert or update, the unique constaint get applied and it will detect that the collection is, in some point in time, having duplicate entry even though at the end of the transaciton it would be just fine.
Examples:
If we have a unique constraint on ValueUniqueA
Then the problem occurs with the 2 use cases below
Use case 1 on insert/update:
Transaciton 1:
insert into TABLE(ID,ValueUniqueA) VALUES(1,1)
Transaction 2:
insert TABLE(ID,ValueUniqueA) VALUES(2,1) <— mysql detect ‘Duplicat entry’
update TABLE(ID,ValueUniqueA) VALUES(1,2)
Use case 2 on multiple update (swap the values on updates):
Transaciton 1:
insert TABLE(ID,ValueUniqueA) VALUES(1,1)
insert TABLE(ID,ValueUniqueA) VALUES(2,2)
Transaction 2:
update TABLE(ID,ValueUniqueA) VALUES(2,1) <— mysql detect ‘Duplicat entry’
update TABLE(ID,ValueUniqueA) VALUES(1,2)
What can be done with hibernate to make those second transactions works???
In Oracle, it is simple you delay the unique constraint at the end of the transaction but mysql?