Nhibernate setting query time out period for commands and pessimistic locking

霸气de小男生 提交于 2019-12-25 02:11:19

问题


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();
    }
}  

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

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

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.


回答1:


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.
    }
}



回答2:


I wonder whether you could adapt this approach to your purposes? It wouldn't be automatic, of course. and it would mean the passed in resourceName would likely need to be a concatenation of your entity type and its PK.

Alternatively, command_timeout looks promising, but I can't see a way to do that (for updates) in any way other than system wide.



来源:https://stackoverflow.com/questions/8102647/nhibernate-setting-query-time-out-period-for-commands-and-pessimistic-locking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!