Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

c# - Should I always use transactions in nhibernate (even for simple reads and writes)?

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();
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...