Archive, NHibernate

NHibernate Criteria Queries

NHibernate’s support for criteria queries provides an extremely powerful query feature into an easy to use package. NHibernate has a rather complete manual that covers criteria queries, which you can checkout here.

The NHibernate documentation has a ton of information packed within it, and can be a little overwhelming for those who are new to NHibernate. So, as an argumentation to the documentation for criteria searching, I will provide a really basic overview of how things work.

The NHibernate session exposes a method called “CreateCriteria”, which accepts a Type and returns an ICriteria. This is the starting point for any criteria query. The Type you pass the method, is the same Type that you are querying for. For example, if you have a business object call “Customer” that we want to search for using criteria, you would:

ICriteria crit = session.CreateCriteria(typeof(Customer));

Now that you have created an ICriteria object to represent your search, you need to start specifying various criteria for the object NHibernate will fetch. This is were the “Add” method comes in handy.

The Add method accepts any ICriterion object, but to help you along NHibernate provides the “Expression” object which has many static methods to help you form your criteria. Continuing with our running example, if you want to select customers who are older than 21 years of age you would:

crit.Add(Expression.Gt("Age", 21));

The above code tell NHibernate that the “Age” property of our Customer object needs to be greater than the value 21. In the above manor, you can use the Add method and the Expression object to specify exactly which objects you want to retrieve.

To actually fetch our objects from the database, you execute the “List” method on the ICriteria object.

IList results = crit.List();

There are many more capabilities of criteria queries in NHibernate that I have not even touched upon, which you can read more about in the official NHibernate documentation.

Never miss an article! Subscribe to my newsletter and I'll keep you updated with the latest content.


About Jason

Jason is an experienced entrepreneur & software developer skilled in leadership, mobile development, data synchronization, and SaaS architecture. He earned his Bachelor of Science (B.S.) in Computer Science from Arkansas State University.
View all posts by Jason →

Leave a Reply

Your email address will not be published. Required fields are marked *