【问题标题】:Why does NHibernate throw "StaleObjectStateException"?为什么 NHibernate 会抛出“StaleObjectStateException”?
【发布时间】:2011-11-02 12:08:18
【问题描述】:

我正在编写项目并使用 NHibernate 3.1

简单测试:

Forum forum = Session.CreateCriteria<Forum>().Add(Restrictions.Eq("UrlName", "reportabug")).UniqueResult<Forum>();
forum.TopicsCount++;
IForumRepository forumRepository = new ForumRepository(SessionFactory);
forumRepository.Update(forum);

public virtual void Update(TEntity entity)
{
    if (!session.Transaction.IsActive)
    {
        TResult result;
        using (var tx = session.BeginTransaction())
        {
            session.SaveOrUpdate(entity)
            tx.Commit();
        }
        return result;
    }
    session.SaveOrUpdate(entity)
}

最后一次更新抛出异常:

StaleObjectStateException was unhandled by user code:
    Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

SQL 查询:

UPDATE Forums
SET    Name = 'Forums Issues (not product support)' /* @p0 */,
       UrlName = 'reportabug' /* @p1 */,
       Description = 'Use this forum to report issues with the online forums application. When reporting an issue please include relevant details such as repro steps, error messages and browser version.' /* @p2 */,
       CategoryId = 'b2cc232c-0d5c-4f35-bb6f-29c67d7d40c2' /* @p3 */,
       TopicsCount = 1 /* @p4 */
WHERE  ForumId = '864046b7-ca57-48c4-8a81-082103223527' /* @p5 */

ForumId 是正确的。 也许这是并发? 有什么想法吗?

【问题讨论】:

  • @ManuPK, tx.Commit(); 线上抛出异常;

标签: c# hibernate nhibernate


【解决方案1】:

StaleObjectStateException 是一种休眠方式,确保数据一致性读取 API here。 Hibernate 维护它更新的对象的version,如果DB 和内存中的版本不匹配,将抛出错误。阅读更多关于乐观锁定机制here

因此,使用此信息调试应用程序。我不熟悉C# 语法,但我认为第二次保存应该在else 条件下。

【讨论】:

  • 没错,我完全错过了:P +1。 @Kovpaev - 删除最后一个session.SaveOrUpdate(entity),不需要它。
  • @Ash Burlaczenko,如果在外部事务的上下文中调用方法 Update(),则需要在方法末尾调用。如果不是,则在“if”块中创建。
猜你喜欢
  • 2019-04-04
  • 2021-12-20
  • 2021-03-05
  • 2021-03-19
  • 2023-03-14
  • 2021-04-09
  • 2014-12-18
  • 2013-12-08
  • 2010-09-27
相关资源
最近更新 更多