The issue is simple in that there are more than one thread which tries to update a record by doing a select before an update for a record. But what happens is that in this case there are two records updated with the same city. If city is made as a unique constraint then the other thread gets an unique constraint violation exception error. So the other thread needs to handle this exception and re process the request.
So how do we make the below piece of code work at high concurrency situations without having a unique constraint kind of approach. This would be reactive i.e. wait for an exception to occur and handle the same. Please share what best practices could be used here to make this work at concurrent loads.
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; } }
|