Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate concurrent insert

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.

like image 871
Viktor Stolbin Avatar asked May 17 '11 12:05

Viktor Stolbin


1 Answers

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.

like image 186
axtavt Avatar answered Nov 12 '22 17:11

axtavt