NHibernate交易和竞争条件 [英] NHibernate transaction and race condition

查看:75
本文介绍了NHibernate交易和竞争条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用NHibernate的ASP.NET应用程序,可以根据用户操作以事务方式更新一些表.涉及到一个日期范围,因此只能对表"Booking"进行一次输入,以指定独占日期.

I've got an ASP.NET app using NHibernate to transactionally update a few tables upon a user action. There is a date range involved whereby only one entry to a table 'Booking' can be made such that exclusive dates are specified.

我的问题是如何防止出现竞价情况,即两个用户动作几乎同时发生,并导致多个币种在预定"中输入> 1个日期.我无法在调用.Commit()之前进行检查,因为我认为仍然会出现竞争状况吗?

My problem is how to prevent a race condition whereby two user actions occur almost simultaneously and cause mutliple entries into 'Booking' for >1 date. I can't check just prior to calling .Commit() because I think that will still leave be with a race condition?

我所能看到的就是在提交之后进行一次检查,然后手动将更改回滚,但这使我口中的味道很差! :)

All I can see is to do a check AFTER the commit and roll the change back manually, but that leaves me with a very bad taste in my mouth! :)

booking_ref(INT)PRIMARY_KEY AUTOINCREMENT

booking_ref (INT) PRIMARY_KEY AUTOINCREMENT

booking_start(DATETIME)

booking_start (DATETIME)

booking_end(DATETIME)

booking_end (DATETIME)

推荐答案

  • 将事务的隔离级别设置为SERIALIZABLE(session.BeginTransaction(IsolationLevel.Serializable),然后检查并插入同一事务中.通常,不应仅在这种情况下将隔离级别设置为可序列化.
    • make the isolation level of your transaction SERIALIZABLE (session.BeginTransaction(IsolationLevel.Serializable) and check and insert in the same transaction. You should not in general set the isolationlevel to serializable, just in situations like this.
      • 在检查并最终插入之前锁定表.您可以通过nhibernate触发SQL查询来实现此目的:

      • lock the table before you check and eventually insert. You can do this by firing a SQL query through nhibernate:

      session.CreateSQLQuery(从预订中(tablockx,holdlock)"作为选择的哑元为null)).AddScalar("dummy",NHibernateUtil.Int32); 这将仅锁定该表以在该事务期间进行选择/插入.

      session.CreateSQLQuery("SELECT null as dummy FROM Booking WITH (tablockx, holdlock)").AddScalar("dummy", NHibernateUtil.Int32); This will lock only that table for selects / inserts for the duration of that transaction.

      希望有帮助

      这篇关于NHibernate交易和竞争条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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