Question

I am retrieving a list of objects in hibernate using Criteria API. However I need lock on those objects as another thread executing at the same time will get the exact objects and only one of the thread will succeed in absence of a pessimistic lock.

I tried like below, but it is not working.

List esns = session
    .createCriteria(Reddy_Pool.class)
    .add(Restrictions.eq("status", "AVAILABLE"))
    .add(Restrictions.eq("name", "REDDY2"))
    .addOrder(Order.asc("id"))
    .setMaxResults(n)
    .setLockMode(LockMode.PESSIMISTIC_WRITE) //not working at all
    .list();

Update: I am performing an update after this statement, so that I would like both threads to read different rows or at least second thread should wait till first thread completes with the transaction and leaves the lock.

And the hibernate generated query is below.

Hibernate: select this_.id as id1_0_, this_.name as name1_0_, 
this_.orderitem_id as orderitem3_1_0_, this_.status as status1_0_, 
this_.store as store1_0_, this_.vendor as vendor1_0_, this_.version as version1_0_ 
from reddy_pool this_ 
where this_.status=? and and this_.name=? order by this_.id asc limit ?

Update: It seems a bug in 3.5.2 version as Pascal Thivent (Thanks a lot Pascal) mentioned, I have joined as member and watching the issue. Hopefully it will be included in the next release.

However I tried using another approach here with session.buildLockRequest()... but I couldn't quite figure out how to use it and using below code is not having any effect at all.

for (int i=0; i < n; i++)
    session.buildLockRequest(LockOptions.UPGRADE).lock(esns.get(i));
Was it helpful?

Solution

What version of Hibernate are you using? Could this be HHH-5275? Are you sure that the FOR UPDATE statement isn't generated? Can you show the generated SQL?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top