hibernatehqlpessimistic-locking

Pessimistic Write Locking not working in Hibernate


Am a newbie to hibernate.

I have two transactions that work on the same record of the db

Transaction 1 : reads the entity E. Applies Lock


    getCurrentSession().buildLockRequest(
                    new LockOptions(
                        LockMode.PESSIMISTIC_WRITE
                    )
                )
                .setTimeOut(
                    Session.LockRequest.PESSIMISTIC_NO_WAIT
                )
                .lock(a);

Transaction 2 : edits the row in a new transaction and commits changes to E

for(Arial a : arials) {
            getCurrentSession().buildLockRequest(
                    new LockOptions(
                        LockMode.PESSIMISTIC_WRITE
                    )
                )
                .setTimeOut(
                    Session.LockRequest.PESSIMISTIC_NO_WAIT
                )
                .lock(a);
a.setUpdatedCount(count);
getCurrentSession().merge(a);
        }

Transaction 1 : works on the copy of E obtained earlier, makes a few changes and saves to DB.

a.setUpdatedCount(oldCount);
getCurrentSession().merge(a);

Transaction 1 ends up overwriting changes made in Transaction 2.

I have applied pessimistic locks in both cases, so which ever one starts first should wait for the other to finish and read the updated record before committing. But this doesn't seem to happen. What am I doing wrong?

Thank you in advance for your time.


Solution

  • For anyone facing the same issue, what helped me was to make a change on the criteria object, instead of the entity.

    query.setLockMode(LockMode.PESSIMISTIC_WRITE);
            Arial a = (Arial) query.uniqueResult();