简体   繁体   中英

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.

It is not usual to have multiple transactions on a single session even in 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.
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.
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 .

No issues although it's unusual. Bear in mind that the session should be discarded if any of the transactions rolls back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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