Is it nessecary to set FlushMode.Commit when using ITransactions?

I have built an NHibernate infrastructure for using Web and Desktop applications.

However, I would like to know if it is necessary to use FlushMode.Commit whenever transactions are used.

Would be a problem if I have the default FlushMode.Auto when getting or creating an ISession?

I have read the following: "Set the session's flush mode to Commit to avoid unnecessary trips to the database when using transactions.".

However, I would like somebody to assure me that as far as functionality the FlushMode.Auto also does the job.

Is it just a performance issue for avoiding the unnecessary trips to the database?

I might live with it.

Please give me your light!

Upvotes: 1

Views: 238

Answers (1)

Frédéric
Frédéric

Reputation: 9854

TL;DR

No, it is not necessary to change flush mode. Leave it as Auto if unsure. You will avoid bugs.

Full explanation

The default flush mode Auto works as described here:

From time to time the ISession will execute the SQL statements needed to synchronize the ADO.NET connection's state with the state of objects held in memory. This process, flush, occurs by default at the following points

  • from some invocations of Find() or Enumerable()
  • from NHibernate.ITransaction.Commit()
  • from ISession.Flush()

This logic is done for ensuring that querying the DB will not return stale data, in regards to what have been done into the current transaction.

Except when you explicity Flush(), there are absolutely no guarantees about when the Session executes the ADO.NET calls, only the order in which they are executed. However, NHibernate does guarantee that the ISession.CreateQuery(..) methods will never return stale data; nor will they return the wrong data.

Changing the default flush mode may cause your queries inside a transaction to return data not tacking into account what have been previously done in the same transaction.

Unless your are quite sure you would not be bitten by any bug due to stale data returned by subsequent queries in the same transaction, better leave the flush mode as Auto.

Changing the flush mode for limiting SQL round-trips inside a transaction would requires to check all current transactions and add explicit calls to Flush before queries needing to take into account what have been previously done in their transaction. Then hope that any new development will not forget to do it too. And so, not only you will not necessarily save many SQL round-trip, but also you will create new opportunities for bugs.

Personally I consider it is not worth changing the default flush mode in the hope of reducing SQL round-trips. Especially if you do not check it does it significantly or marginally in the case of your application.

Upvotes: 1

Related Questions