#henrik

development and technology stuff

NHibernate Transactions

For my ASP.NET project I'm using the nice NHibernate template from Billy McCafferty. Work's exactly the way I want. But I noticed one thing which isn't that good after all. A transaction rollback does not work. One ends up with all the changes persisted to the database. The problem was, that the NHibernate example uses a session.flush() even after a rollback - which is not the recommended by the NHibernate documentation. The comments on the CodeProject page were quite helpful, as well as a discussion at stackoverflow. The solutiion for this problem: Just don't flush after rollback.

public void RollbackTransaction() {
    ITransaction transaction = ContextTransaction;
    try {
        if (HasOpenTransaction()) {
            transaction.Rollback();
        }
        ContextTransaction = null;
    }
    finally {
        CloseSession(false);
    }
}

public void CloseSession(bool flush)
{
    ISession session = ContextSession;
    if (session != null && session.IsOpen)
    {
        if(flush)
            session.Flush();
        session.Close();
    }
    ContextSession = null;
}

Filed under  //   Development   NHibernate   c#  

NHibernate Transformers

NHibernate is awesome. I'm using it for the first time in a ASP.NET project. Today I found a nice feature in combination with native SQL queries. One can return unmanaged entities for a native SQL query - with automatic mapping - excellent! See the documentation on using Transformers: (NHibernate native SQL queries)

sess.CreateSQLQuery("SELECT name, birthdate FROM CATS")
        .SetResultTransformer(Transformers.AliasToBean(typeof(CatDTO)))

public class CatDTO {
    public string Name {
        get {}
        set {}
    }
    public DateTime Birthdate {
        get {}
        set {}
    }
}

Just create Properties using the same name as the columns of the query in the POCO and you're done. And the extra nice thing. Exactly the same approach in the original Java version (Hibernate native SQL queries).

Filed under  //   Development   NHibernate   Other   c#