NHibernate Query Example using CreateCriteria


I’m a big fan of NHibernate. I love how it abstracts out the data portion of your application and allows you to work from the perspective of the domain rather than the database.

So in building my domain repositories, I have several options to query the database using NHibernate:

  • I can use HQL in CreateQuery.
  • I can use named queries in GetNamedQuery.
  • I can use SQL directly in CreateSqlQuery.
  • I can use the type of object in a CreateCriteria.

Short of using Ayende’s NHibernate Query Generator to strongly type my HQL queries, I like using the CreateCriteria call.

The Example

To begin with, I’m not a fan of generic repository interfaces with a ton of generics-based CRUD operations (IRepository). I’d rather just limit my repository code to what is needed for operating with that aggregate root (driven by the domain, of course).

For this example, I have an interface in my domain project called CommissionPeriodRepository (yes, no ‘I’ in front of my interfaces – again, personal preference… lol). The implementation class, NHibernateCommissionPeriodRepository, resides in an NHibernate specific project implementing the repository interfaces. Finally, I’m assuming that the NHibernate session (Unit of Work is used here, but is NHibernate specific) is managed by the calling application, committing and rolling back changes as necessary. 

    public class NHibernateCommissionPeriodRepository : CommissionPeriodRepository
    {
        #region CommissionPeriodRepository Members

  
  
        public CommissionPeriod GetCommissionPeriodFor(DateTime date)
        {
            return UnitOfWork.GetCurrentSession()
                .CreateCriteria(typeof (CommissionPeriod))
                .Add(Expression.Lt("Startdate", date))
                .Add(Expression.Ge("Enddate", date))
                .UniqueResult<CommissionPeriod>();
        }

  
  
        #endregion
    }

Pretty much all the code is doing is:

  1. Pulling the current NHibernate session.
  2. Creating a criteria object for a CommissionPeriod domain object.
  3. Pulling the unique CommissionPeriod object that has a start date less than that passed in date and an end date greater than or equal to it.

That’s it. Simple stuff. Gotta love it.

ReSharper Keymappings