Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple NHibernate sessions in one Transanction

I need to enlist several NHibernate sessions in one transaction. Currently I do the following:

1) Create a SQL connection, dbConn;

2) Call ISession session = ISessionFactory.OpenSession(dbConn) to create a first session;

3) Call session.BeginTransaction() to begin a transaction.

4) Later in the code, I create a new session with the same connection:

ISession session2 = ISessionFactory.OpenSession(dbConn)

When I attempt to run any query against session2, I get the following error message:

ExecuteReader requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized.

NHibernate doesn't seem to enlist the second ISession (or, more specifically, the Command object that it creates for that session) in the open transaction, even though it does reuse the same connection.

Is there any way to have multiple sessions within the same transaction?

I cannot use a single session because I have a long-running task that loads and creates over 1 million objects. If I use one ISession, the performance degrades from 3000 database requests per second to 20, due to performance degradation of NHibernate Flushes. To solve this I'd like to create short-lived sessions and dispose them quickly.

However, the entire process is wrapped into a transaction. If I create independent subsequent sessions with their own connections, they bump against the table locks held by the first transaction and freeze. To solve this I need these sessions running within the same transaction.

like image 201
Alex Avatar asked May 03 '13 01:05

Alex


1 Answers

things you can do

  • session.GetSession() to create child sessions with the same context (connection, transaction, mode)
  • if you don't need Cascading use StatelessSession which is meant for this
  • use session.Clear(); after every 50 objects or so
like image 109
Firo Avatar answered Oct 15 '22 10:10

Firo