Hello, we are trying to use Hibernate with optimistic concurrency control. Our entities have the "@version" annotation so that hibernate can check if there has been an update from user B during the timespan from when user A has loaded the entity until user A commits his changes. So let's assume that user A loads the entity (with the version 1, then user B commits his changes (setting the version in the db to 2), the user A tries to commit. In that case, Hibernate throws the infamous StaleObjectStateException, because there is a conflict.
Now let's now assume that user A wants to accept the changes of user B. So he does something like:
try { Session session = transactionManager.getSession(); org.hibernate.Transaction tx = session.beginTransaction(); session.persist(entity); tx.commit();
}catch(StaleObjectStateException ex){
String entityName = ex.getEntityName(); Serializable identifier = ex.getIdentifier(); tx.rollback(); BusinessObject modifiedObject = entity; BusinessObject dataBaseState = (BusinessObject) session.get(entityName, identifier); //System.out.println(modifiedObject.getVersion()); //displays 1 //System.out.println(dataBaseState.getVersion()); //displays 2
session.refresh(modifiedObject); //System.err.println(modifiedObject.getVersion()); //displays 2
//Try to commit again Session session = transactionManager.getSession(); org.hibernate.Transaction tx = session.beginTransaction(); session.persist(); tx.commit(modifiedObject); //Throws an StaleObjectStateException again, in spite of having identical version numbers!!!!! }
Without any other user interfering, this again throws a StaleObjectStateException, although after session.refresh(entity), the entity is up-to-date to the database (in particular, the version is set to 2).
Why is it that Hibernate sees a conflict although the entity is up-to-date to the database?
Many thanks!
|