I faced a problem. I have an App with Hibernate that loads data from XML files into tables in concurrent mode. Some part of data could be same and could be inserted from differnet threads. Each thread works in its own long-play transaction. There's an issue when two or more treads try to commit transaction. For example two threads inserted records into table City that has constraint on NAME field. It means that ConstraintViolationException occurs on flush() or commit(). I want to automatically handle this collisions and want new problem objects to be replaced with older already inserted objects. Is this possible? I look at saveOrUpdate() and optimistic version control in Hibernate.
I assume that you use one of MVCC-based DBMS.
If transaction isolation level is not higher than READ COMMITTED, you can reduce probability of conflict by issuing a query to check for existence of Cities with the same name
before inserting the new one.
Note that saveOrUpdate()
can't help here, since name
is not a primary key. Also note that you cannot prevent conflict at all (at least without using some DBMS-specific features), since basically it's an example of write skew anomaly, which can't be prevented in MVCC-based DBMS.
Also, if atomicity of importing XML file is not critical, you can break long transaction into several shorter ones, and simple retry them in a case of constraint violation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With