开发者

Concurrent incrementation of integer column on update with NHibernate

开发者 https://www.devze.com 2023-02-28 16:30 出处:网络
I have a Posts table with a Version number column to keep track of the nth revision for each record. Every time a row is updated, I would like its Version number to be incremented.

I have a Posts table with a Version number column to keep track of the nth revision for each record. Every time a row is updated, I would like its Version number to be incremented.

Presently, I am incrementing the column in my application logic, but because post.Version += 1; does not equate to UPDATE Posts SET Version = Version + 1..., I am worried that two concurrent updates will result in only one Version increment.

Solving this is easy with a manual SQL expression (as above) or an update trigger, but I would rather have Fluent NHibernate take care of this for me, if possible.

Using a transaction for the update would not prevent two simultaneo开发者_开发技巧us reads from both seeing version "7", and both deciding that the next value should be 8. Thus, two updates to version 7 could result in a value of 8, instead of 9.

How do I design or map an auto-incrementing integer column that is concurrency-safe?


It's already baked into NHibernate. Check NH docs on <version> tag and on Optimistic Concurrency Control.


Why are you managing a Version column manually?

Use NHibernate's support for optimistic concurrency (see http://www.nhforge.org/doc/nh/en/index.html#mapping-declaration-version) and you'll get that for free (along with a more correct behavior IMO)

0

精彩评论

暂无评论...
验证码 换一张
取 消