views:

84

answers:

1

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 atleast 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));
+1  A: 

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?

Pascal Thivent
This is the query generated by hibernate (Version: 3.5.2 Final) And yes, this seems like HHH-5275, so does this means we have to wait till next version? :(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 ?
Reddy
Thanks Pascal. I have tried another approach to use session to place lock (see second update in my question) but it is not working too.
Reddy
I had to swap out my criteria query as well because of this issue. It seems like a big deal - why is HH-5275 noted as minor?
Anthony Bishopric
@Anthony I don't know. IMO, the best thing you can do is to vote for the issue and to leave a comment on Jira.
Pascal Thivent
@Pascal will do.
Anthony Bishopric