简体   繁体   English

NHibernate:单个会话上有多个事务

[英]NHibernate: Multiple Transactions on a single session

I want to know if there is any issue by creating several transactions on a single session, like this: 我想通过在单个会话上创建多个事务来了解是否存在任何问题,如下所示:

using (var session = factory.OpenSession())
{
    using (var trans1 = session.BeginTransaction())
    {
        .....
        trans1.commit();
    }

    using (var trans2 = session.BeginTransaction())
    {
        .....
        trans2.commit();
    }

    using (var trans3 = session.BeginTransaction())
    {
        .....
        trans3.commit();
    }

    using (var trans = session.BeginTransaction())
    {
        .....
        // trans1.commit();
    }
}

is that possible or must I open a new session object per transaction? 有可能吗?是否必须为每个事务打开一个新的会话对象?

Thanks for your help. 谢谢你的帮助。

Yes what you are doing is just fine. 是的,您所做的一切都很好。

What nhibernate does not support are multiple nested transactions. nhibernate不支持多个嵌套事务。

It is not usual to have multiple transactions on a single session even in NHibernate. 即使在NHibernate中,在单个会话上进行多个事务也并不常见。 Also from personal experience I can say it is not a good idea to reuse sessions in any other situation. 同样根据个人经验,我可以说在任何其他情况下重用会话不是一个好主意。

I recommend to keep the workflow as simple as possible to avoid any side-effects: 我建议保持工作流程尽可能简单,以避免任何副作用:

  • open session 公开会议
  • open transaction 公开交易
  • use your entities 使用您的实体
  • commit transaction 提交交易
  • rollback in case of exception 发生异常时回滚
  • close/flush session (always) 关闭/刷新会话(始终)

The most common strategy in a web environment is to have session per request. Web环境中最常见的策略是每个请求都具有会话。
When it cones to transactions, it really depends on your use-case. 当涉及事务时,实际上取决于您的用例。
What you are doing is fine, or otherwise nhibernate wouldn't separate session from transaction. 您正在执行的操作很好,否则nhibernate不会将会话与事务分开。
but yet again, it depends on your business case situation. 但同样,这取决于您的业务案例情况。

I suggest you to wrap the session.BeginTransaction() with IDisposable , so on Dispose you make sure to commit transaction . 我建议您使用IDisposable包装session.BeginTransaction() ,因此在Dispose请确保提交transaction。

No issues although it's unusual. 没问题,尽管很不寻常。 Bear in mind that the session should be discarded if any of the transactions rolls back. 请记住,如果任何事务回滚,则应丢弃该会话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM