I have a problem where I want to read an object from the database using Hibernate, change a value, and save the object. If changing the value takes some time, what's the best way to ensure the underlying object in the database has not changed? I am doing this in one transaction (and one session).
The code looks something like:
// Load from DB
Criteria crit = session.createCriteria( Dummy.class ).add( Restrictions.eq("id", 5) );
Dummy val = crit.uniqueResult();
// Processing time elapses.
// Update value of dummy.
val.x++;
// Save back to database. But what if someone modified the row with ID = 5 in the meantime, and changed the value of x?
session.saveOrUpdate( val );