Chapter 7. Retrieving objects efficiently
This chapter covers
- NHibernate query features
- HQL, criteria, and native SQL
- Advanced, reporting, and dynamic queries
- Runtime fetching and query optimization
Queries are the most interesting part of writing good data access code. A complex query may require a long time to get right, and its impact on the performance of an application can be tremendous. As with regular SQL, writing NHibernate queries becomes much easier with experience.
If you’ve been using handwritten SQL for a number of years, you may be concerned that ORM will take away some of the expressiveness and flexibility you’re used to. This is seldom the case; NHibernate’s powerful query facilities allow you to do almost anything you would in SQL, and in some cases more. For the rare cases where you can’t make NHibernate’s own query facilities do exactly what you want, NHibernate allows you to retrieve objects using your database’s native SQL dialect.
In section 4.4, we mentioned that there are three ways to express queries in NHibernate. First is the HQL :
Next is the ICriteria API:
Finally, there is direct SQL, which automatically maps result sets to objects: