如何使用Criteria API指定悲观锁定?

Red*_*ddy 9 hibernate hibernate-criteria

我正在使用Criteria API检索hibernate中的对象列表.但是我需要锁定这些对象,因为同时执行的另一个线程将获得确切的对象,并且只有一个线程将在没有悲观锁定的情况下成功.

我尝试过如下,但它不起作用.

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();
Run Code Online (Sandbox Code Playgroud)

更新:我在此语句之后执行更新,因此我希望两个线程都读取不同的行,或者至少第二个线程应该等到第一个线程完成事务并离开锁.

而hibernate生成的查询如下.

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 ?
Run Code Online (Sandbox Code Playgroud)

更新:这似乎是3.5.2版本中的一个错误,因为Pascal Thivent(非常感谢Pascal)提到过,我已经加入成为会员并观看了这个问题.希望它将包含在下一个版本中.

然而,我尝试使用另一种方法session.buildLockRequest()...但我无法弄清楚如何使用它并使用下面的代码根本没有任何影响.

for (int i=0; i < n; i++)
    session.buildLockRequest(LockOptions.UPGRADE).lock(esns.get(i));
Run Code Online (Sandbox Code Playgroud)

Pas*_*ent 4

您使用什么版本的 Hibernate?这可能是HHH-5275吗?您确定该FOR UPDATE语句没有生成吗?你能显示生成的 SQL 吗?