Nhibernate为命令和悲观锁定设置查询超时时间 [英] Nhibernate setting query time out period for commands and pessimistic locking

查看:271
本文介绍了Nhibernate为命令和悲观锁定设置查询超时时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望为SQL指定特定的命令超时(或LOCK_TIMEOUT),一旦达到此超时,就必须在nHibernate中引发异常(或警报).
以下是我编写的示例伪代码:

I wish to specify a specific command timeout (or LOCK_TIMEOUT) for an SQL and once this time out is reached an exception (or alert) has to be raised in nHibernate.
The following is an example pseudo-code what I have written:

using (var session = sessionFactory.OpenSession()) {
    using (var sqlTrans = session.BeginTransaction()) {
        ICriteria criteria = session.CreateCriteria(typeof(Foo));
        criteria.SetTimeout(5); //Here is the specified command timout, eg: property SqlCommand.CommandTimeout
        Foo fooObject = session.Load<Foo>(primaryKeyIntegerValue, LockMode.Force);
        session.SaveOrUpdate(fooObject);
        sqlTrans.Commit();
    }
}  

在SQL Server中,我们通常使用以下SQL来实现此目的:

In SQL server we used to achieve this using the following SQL:

BEGIN TRAN
SET LOCK_TIMEOUT 500   
SELECT * FROM Foo WITH (UPDLOCK, ROWLOCK) WHERE PrimaryKeyID = 1000001

如果PrimaryKeyID行将已锁定在其他事务中,则SQL Server将显示以下错误消息:

If PrimaryKeyID row would have locked in other transaction the following error message is being shown by SQL Server:

Msg 1222, Level 16, State 51, Line 3
Lock request time out period exceeded

同样,我希望使用nHibernate显示锁定超时或命令超时信息.请帮助我实现这一目标.
预先感谢您的帮助.

Similarly I wish to show a lock time out or command time out information using nHibernate. Please help me to achieve this.
Thanks in advance for your help.

推荐答案

要实现悲观锁定,您需要使用ICritiera获取对象的详细信息.
更改后的代码如下:

To achieve pessimistic locking you need to get the details of object using ICritiera.
The altered code is given below:

using (var session = sessionFactory.OpenSession()) {
    using (var sqlTrans = session.BeginTransaction()) {
        ICriteria criteria = session.CreateCriteria<Foo>();
        criteria.Add(Restrictions.Eq(fieldOnWhichYouWishToGetTheLock, fieldValue));
        criteria.SetLockMode(LockMode.Upgrade);
        criteria.SetTimeout(5);
        Foo fooObject = (Foo)criteria.List<Foo>();
        //Make the changes to foo object and save as usual.
    }
}

这篇关于Nhibernate为命令和悲观锁定设置查询超时时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆