How can I ensure that the value being updated with Hibernate hasn't changed in the meantime since I read it?

I have a problem where I want to read an object from the database using Hibernate, change the value and save the object. If it takes a while to change the value, what's the best way to ensure that the underlying object in the database doesn't change? I am doing this in one transaction (and one session).

The code looks something like this:

// 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 );

      

+1


source to share


2 answers


I would recommend optimistic blocking. you add a "version" property to your object and then hibernate does the update operation at the end and checks that the version hasn't changed since the object was read. generally much better than pessimistic locking (nothing like finding those db deadlocks!).



Of course, the question remains, what are you planning to do if the object has changed?

+2


source


You can use the pessimistic lock, although I would not, but it might be useful in your case.

Since your object is being fetched from the database, you need to lock the database so that no one else changes your object while working with it.

To do this, you need to lock your object.

session.lock( myObject , LockMode.UPGRADE );

      

Try it.



EDIT

It could be more than you:

// Load from DB

Criteria crit = session.createCriteria( Dummy.class ).add( Restrictions.eq("id", 5) );

crit.setLockMode( LockMode.UPGRADE  ); // issues a SELECT ... for UPDATE... 

Dummy val = crit.uniqueResult();

 etc.etc

      

Criteria.setLockMode ()

0


source







All Articles