NHibernate - Is ITransaction.Commit Really Necessary?

I just started learning NHibernate 2 days ago and I'm looking for a CRUD method that I wrote based on a tutorial. My insertion method:

        using (ISession session = Contexto.OpenSession())
        using (ITransaction transaction = session.BeginTransaction())
        {
            session.Save(noticia);
            transaction.Commit();
            session.Close();
        }

The full "Contexto" code is here: http://codepaste.net/mrnoo5

My question is: do I really need to use the transaction ITransaction = session.BeginTransaction () and transaction.Commit (); ?

I ask for this because I tested running the web application without these two lines, and I successfully inserted new entries.

If possible, can someone explain to me the purpose of Itransaction and the Commit method too?

thank

+2
source share
3 answers

ITransaction = session.BeginTransaction() , .

, , ? ?

Nhib...

:

ISession sess = factory.OpenSession();
ITransaction tx; 
try 
{ 
    tx = sess.BeginTransaction(); //do some work ... 
    tx.Commit(); 
} 
catch (Exception e) 
{ 
    if (tx != null) 
    tx.Rollback(); 
    throw;
} 
finally 
{ 
    sess.Close(); 
}

ISession , . ISession . NHibernate.ISessionFactory

+3

NHibernate:

using (ISession session = sessionFactory.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
    //Do the work here
    transaction.Commit();
}

, ( )

- , , , Dispose , , .

, - , , .

+9

, Commit() , .

ITransaction = session.BeginTransaction() transaction.Commit();?

, , .

- , .

because the session will commit the changes when it is deleted at the end of the using statement.

Anyway, this is how I would save:

using (ISession session = Contexto.OpenSession())
{
    using (ITransaction transaction = session.BeginTransaction())
    {
        try
        {
            session.Save(noticia);
            transaction.Commit();
        }
        catch(HibernateException)
        {
            transaction.Rollback();
            throw;
        }
    }
}
+1
source

All Articles