rollback()后的NHibernate 3会话状态

发布于 2024-10-06 18:03:23 字数 703 浏览 0 评论 0原文

我有一个问题。

using (var tran = repository.Session.BeginTransaction())
{
    try
    {
        repository.Save(entity);
        tran.Comit();
    }
    catch(Exception)
    {
        tran.Rollback();
        throw;
    }    
}

using (var tran = repository.Session.BeginTransaction())
{
    try
    {
        repository.GetById(id);
        tran.Comit();
    }
    catch(Exception)
    {
        tran.Rollback();
        throw;
    }    
}

当我尝试在异常和第一个 using 块中的 tran.rollback() 后通过 ID 获取实体时,我收到更新异常。因此,NHibernate 尝试从第一个 using 块更新第二个 using 块中的实体。

为什么?我执行了 tran.Rollback() 。我也必须执行Session.Clear()吗?

I have a problem.

using (var tran = repository.Session.BeginTransaction())
{
    try
    {
        repository.Save(entity);
        tran.Comit();
    }
    catch(Exception)
    {
        tran.Rollback();
        throw;
    }    
}

using (var tran = repository.Session.BeginTransaction())
{
    try
    {
        repository.GetById(id);
        tran.Comit();
    }
    catch(Exception)
    {
        tran.Rollback();
        throw;
    }    
}

When I try to get an entity by ID after exception and tran.rollback() in the first using block, I get an update exception. So NHibernate is trying to update the entity from the first using block in the second using block.

Why? I did the tran.Rollback(). Must I do Session.Clear(), too?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

疧_╮線 2024-10-13 18:03:23

根据 Hibernate 的 API,当 Hibernate Session 抛出异常时,您必须关闭该 Session 并创建一个新的。另外,当您回滚 Hibernate 事务时,以后不得提交该事务或刷新会话 - 您必须在新会话中重新开始。

特别是(这是一个实现细节,所以不要依赖它),回滚后,Hibernate 会话仍然具有自事务开始以来创建/修改的实体 - Hibernate 不会遍历您的实体并恢复您所做的所有更改。因此,如果您回滚事务,然后刷新会话,Hibernate 将提交您认为已回滚的实体更改。如果您想通过尝试破解此行为(例如通过清除会话)来玩火,请小心。最好从新的会话开始。

According to Hibernate's API, when a Hibernate Session throws an exception, you must close the Session and create a new one. Also, when you roll back a Hibernate transaction, you must not later commit it or flush the Session - you must start over in a new Session.

In particular (and this is an implementation detail so don't rely on it), after a rollback, the Hibernate Session still has entities created/modified since the transaction began - Hibernate doesn't go through your entities and revert all changes you made. Therefore, if you roll back the transaction and then flush the Session, Hibernate will commit entity changes that you thought you rolled back. If you are going to play with fire by trying to hack around this behavior (such as by clearing the Session), beware. It's best to just start over with a new Session.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文