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 :

session.CreateQuery("from Category c where c.Name like 'Laptop%'");

Next is the ICriteria API:

session.CreateCriteria(typeof(Category))
.Add( Expression.Like("Name", "Laptop%") );

Finally, there is direct SQL, which automatically maps result sets to objects:

session.CreateSQLQuery(
"select {c.*} from CATEGORY {c} where NAME like 'Laptop%'",
"c",
typeof(Category));

7.1. Executing queries

 

7.2. Basic queries for objects

 

7.3. Joining associations

 

7.4. Writing report queries

 

7.5. Advanced query techniques

 
 
 

7.6. Native SQL

 
 

7.7. Optimizing object retrieval

 
 
 
 

7.8. Summary

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest