NHibernate: Modifying different fields of an entity from two sessions
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 NHiber开发者_JS百科nate'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.
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 locking
More information here.
精彩评论