views:

80

answers:

1

I know that for multi part writes, I should be using transactions in nhibernate. However what about for simple read and writes (1 part) ... I've read that it's good practice to always use transactions. Is this required?

Should I do the following for a simple read ?? or can I just drop the transcaction part all togather ?

public PrinterJob RetrievePrinterJobById(Guid id)
            {
                using (ISession session = sessionFactory.OpenSession())
                {
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        var printerJob2 = (PrinterJob) session.Get(typeof (PrinterJob), id);
                        transaction.Commit();

                        return printerJob2;
                    }
                }
            }

or

public PrinterJob RetrievePrinterJobById(Guid id)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
               return (PrinterJob) session.Get(typeof (PrinterJob), id);

            }
        }

What about for simple writes?

public void AddPrintJob(PrinterJob printerJob)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(printerJob);
                    transaction.Commit();
                }
            }
        }
+4  A: 

Best recommendation would be to always use a transaction. This link from the NHProf documentation, best explains why.

When we don't define our own transactions, it falls back into implicit transaction mode, where every statement to the database runs in its own transaction, resulting in a large performance cost (database time to build and tear down transactions), and reduced consistency.

Even if we are only reading data, we should use a transaction, because using transactions ensures that we get consistent results from the database. NHibernate assumes that all access to the database is done under a transaction, and strongly discourages any use of the session without a transaction.

(BTW, if you are doing serious NHibernate work, consider trying out NHProf).

driis