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;
}
}
当我尝试在异常和第一个 using
块中的 tran.rollback()
后通过 ID 获取实体时,我收到更新异常。因此,NHibernate 尝试从第一个 using
块更新第二个 using
块中的实体。
为什么?我执行了 tran.Rollback() 。我也必须执行Session.Clear()
吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 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.