rollback()之后的NHibernate 3会话状态 [英] NHibernate 3 session state after rollback()

查看:77
本文介绍了rollback()之后的NHibernate 3会话状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题.

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;
    }    
}

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

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.

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

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

推荐答案

根据Hibernate的API,当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.

特别是(这是一个实现细节,所以不要依赖它),回滚后,自事务开始以来,Hibernate会话仍然具有创建/修改的实体-Hibernate不会遍历您的实体并还原所有内容您所做的更改.因此,如果您回滚事务然后刷新会话,则 Hibernate将提交您认为已回滚的实体更改.如果您打算通过尝试破解此行为(例如通过清除Session)来玩火,请当心.最好从一个新的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.

这篇关于rollback()之后的NHibernate 3会话状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆