将对象重新附加到会话时出现 NHibernate NonUniqueObjectException(使用 Lock)
基本执行顺序:
- 查询
PersistentObjects
集合,然后将其与会话分开缓存。 - 该集合被传递到一个模块,该模块需要将它们重新附加到会话,以便延迟加载某些属性(使用
session.Lock(obj, LockMode.None)
)。 - 模块完成处理后,另一个模块会尝试
SaveOrUpdate
一个UserSetting
对象,其中包含初始化操作的用户的一些使用统计信息。 - 在
session.Flush()
上,NHibernate 会抛出NonUniqueObjectException
。
我发现解决此问题的一种方法是使用以下命令获取对象的新副本:
obj = session.Get(obj.GetType(), (obj as PersistentObject).Id);
而不是使用 session.Lock
重新附加。 然而,这不是最佳的,因为某些记录集可能非常大,并且单独重新获取每个对象可能会拖累性能。
非唯一对象是仅存在于 PersistentObject
类中的引用对象,而不存在于 UserSetting
类中。 所以我不明白为什么刷新会导致这个异常。
我尝试在模块使用完缓存的对象后逐出它们,但这没有帮助。
有谁知道将对象附加到会话可以避免此问题的更好方法?
Basic order of execution:
- A collection of
PersistentObjects
is queried then cached separately from the session. - The collection is passed to a module that needs to reattach them to the session in order to lazily load some of the properties (using
session.Lock(obj, LockMode.None)
). - After the module has completed processing, another module attempts to
SaveOrUpdate
aUserSetting
object with some usage statistics for the user who initialized the action. - On
session.Flush()
NHibernate throws aNonUniqueObjectException
.
I've found that one way of working around this issue is to get new copies of the objects with:
obj = session.Get(obj.GetType(), (obj as PersistentObject).Id);
instead of reattaching with session.Lock
. However, this is non-optimal as some of the record sets are potentially quite large, and re-getting each object individually could become a performance drag.
The object which is non-unique is a referenced object that exists only on the PersistentObject
class, and not the UserSetting
class. So I cannot understand why a flush would cause this exception.
I've tried evicting the cached objects after the module is done with them, but this does not help.
Does anyone know of a better way to attach objects to the session that could avoid this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用新的会话(或事务)来处理每个项目并更新 UserSetting 吗? 这可能会阻止 NonUniqueException。
干杯,
-马丁
Can you use a fresh session (or transaction) for processing each item and for updating the UserSetting? This would probably prevent the NonUniqueException.
Cheers,
-Maarten