Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate: Session.Save and Transaction.Commit

Tags:

nhibernate

Is there a difference between Session.Save and Transaction.Commit ?

When I should use which?

It seems that sometimes Session.Save must use in conjunction with Transaction.Commit, sometimes no. Can anyone tell why this is so?

like image 386
Graviton Avatar asked Aug 26 '09 07:08

Graviton


1 Answers

They're differenrt-- Session.Save saves an object and Transaction.Commit commits a bunch of work (multiple Gets, Loads, Saves, Updates, etc).

You'll want to use both. Here's a quick explanation with a link for more reading. The NHibernate documentation says the following:

In an ISession, every database operation occurs inside a transaction that isolates the database operations (even read-only operations).

If you don't explicitly define your transaction, one will be created implicitly every time you read from or write to the database. Not very efficient. So even if you're just reading, you'll want to put everything inside a transaction and commit the transaction when you're done. Ayende Rahien explains further in this blog post.

When you look at some code samples out there, it may seem like people aren't using transactions but they may just be beginning/committing the transaction outside of the code you're looking at. In my ASP.Net MVC app, for example, I use an action filter (TransactionAttribute) to handle the transaction outside of my Controller Actions.

like image 133
Ben F Avatar answered Nov 20 '22 00:11

Ben F