我正在使用hibernate 3.5.4,SQL Server 2012并尝试为X实体构建一个控制同时更新的方法。
public void update(){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.buildLockRequest(LockOptions.UPGRADE.setLockMode(LockMode.PESSIMISTIC_WRITE)
.setTimeOut(1000)).lock(this); // Set TimeOut 1s
System.out.print("Locked\n");
try{
Thread.sleep(10000); // sleep 10s
} catch (Exception e){};
//Do something here
transaction.commit();
session.close();
System.out.print("Unlocked\n");
}
我有两个具有相同id = 1的X实例。
X a = session.get(X.class,1);
X b = session.get(X.class,1);
我希望在a
和b
同时执行update()
方法时获得异常,但不会抛出任何错误。
a.update();
try{
Thread.sleep(1000);
} catch (Exception e){};
b.update();
控制台日志:
Locked
UnLocked
Locked
UnLocked
这是否意味着当setTimeOut
方法仍在等待然后继续而不是因超时而抛出错误时,它的工作方式不正确?