Hibernate simultaneous insertion

I have a problem. I have an application with Hibernate that loads data from XML files into tables in parallel. Some of the data may be the same and may be inserted from differnet streams. Each thread works in its own transaction with long games. There is a problem when two or more runs try to complete a transaction. For example, two threads inserted records into the City table, which has a restriction on NAME . This means that a ConstraintViolationException is thrown on flush () or commit (). I want to automatically handle these conflicts and I want the new task objects to be replaced by the old objects already inserted. Is it possible? I am looking at saveOrUpdate () and optimistic version control in Hibernate.

+7
source share
2 answers

I assume that you are using one of the MVCC-based DBMSs .

If the transaction isolation level does not exceed READ COMMITTED, you can reduce the likelihood of conflict by issuing a request to check for the existence of cities with the same name before inserting a new one.

Please note that saveOrUpdate() will not help here, since name not a primary key. Also note that you cannot prevent a conflict at all (at least not using some DBMS-specific functions), since this is basically an example of writing an anomaly of skew that cannot be prevented in an MVCC-based DBMS.

In addition, if the atomicity of importing an XML file is not critical, you can split the long transaction into several shorter ones and simply repeat them if the restrictions are violated.

+1
source

In such situations, we use the convention of the "insertOrUpdate ()" method with the following common thread. The transaction is executed by the calling method "insertOrUpdate ()" upon return:

 public MyHibernateObject insertOrUpdate(MyHibernateObject newObj, Session s) { String name = newObj.getCityName(); MyHibernateObject existingObj = getByCityName(name, s); if ( existingObj == null ) { s.saveOrUpdate(newObj); return newObj; } else { existing.copyImportantFields(newObj); s.saveOrUpdate(existing); return existing; } } 
0
source

All Articles