NHibernate:从两个会话修改实体的不同字段
我有一个具有多个字段的实体。可以对其执行两种类型的操作:长操作,通常由用户启动,以及短操作,由系统定期运行。这两者都更新实体,但它们涉及不同的领域。
不能有两个并发的长操作或两个并发的短操作。但是系统可能会在进行长操作的同时安排短操作,并且两者应该同时执行。由于他们涉及的领域不同,我相信这应该是可能的。
我认为 NHibernate 的更改跟踪应该可以解决这个问题 - 即,如果一个会话加载一个实体并更新一些字段,而另一个会话加载相同的实体并更新不同的字段,那么两者不会发生冲突。但是,我觉得我不应该依赖于此,因为它听起来像是“优化”或“实现细节”。我倾向于将更改跟踪视为减少数据库流量的优化,我不希望系统的功能依赖于它。另外,如果我决定为该实体实现乐观并发,那么即使我可以保证不存在实际冲突,我也会面临获得 StaleObjectException 的风险。
实现这一目标的最佳方法是什么?我应该将实体分成两部分吗?这不会影响数据库一致性吗(例如,如果数据库中只有实体的“一半”怎么办)?我可以使用 NHibernate 显式设置实体的单个字段吗?我不想依靠变更跟踪来实现功能是错误的吗?
如果重要的话,我正在使用 Fluent NHibernate。
I have an entity with multiple fields. There are two types of actions that may be performed on it: a long one, usually initiated by the user, and a short one, which is periodically run by the system. Both of these update the entity, but they touch different fields.
There can't be two concurrent long operations or two concurrent short operations. But the system may schedule a short operation while a long operation is in progress, and the two should execute concurrently. Since they touch different fields, I believe this should be possible.
I think NHibernate's change tracking should do the trick here - i.e., if one session loads an entity and updates some fields, and another session loads the same entity and updates different fields, then the two will not collide. However, I feel I shouldn't be relying on this because it sounds like an "optimization" or an "implementation detail". I tend to think of change tracking as an optimization to reduce database traffic, I don't want the functionality of the system to depend on it. Also, if I ever decide to implement optimistic concurrency for this entity, then I risk getting a StaleObjectException, even though I can guarantee that there is no actual collision.
What would be the best way to achieve this? Should I split the entity into two? Can't this affect database consistency (e.g. what if only one "half" of the entity is in the DB)? Can I use NHibernate to explicitly set only a single field of an entity? Am I wrong in not wanting to rely on change tracking to achieve functionality?
If it matters, I'm using Fluent NHibernate.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
动态更新
来映射实体。dynamic-update
(可选,默认为 false):指定应在运行时生成 UPDATE SQL,并且仅包含那些值已更改的列。如果启用动态更新,则可以选择乐观锁定策略:
version
检查版本/时间戳列all
检查所有列dirty
检查更改的列none
不使用乐观锁定更多信息 这里。
You could map the entity using
dynamic update
.dynamic-update
(optional, defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed.If you enable dynamic-update, you will have a choice of optimistic locking strategies:
version
check the version/timestamp columnsall
check all columnsdirty
check the changed columnsnone
do not use optimistic lockingMore information here.