The object-relational mapper for .NET

Future<T> Queries with HQL and Criteria

A few days ago Oren Eini and Davy Brion were working in a new feature for NH 2.1 (no a release yet) called Future, in the ICriteria API. You can see and explanation of the job here. Now I’ve committed a complement to enable that use into the IQuery API, for those who prefer to use HQL.

What is Future Query anyway? Future are queries that are kept, waiting to be executed as a group in just one roundtrip, making use of an underlying NHibernate feature: MultiCriteria/MultiQuery.

Let’s have a look to this simple piece of code. You can see both queries sentences, and both are executed in that sentence point against the database producing 2 roundtrips to the database. Nothing weird about this, but what if we can just execute the queries in just one roundtrip?

And now, using Future we can hold the execution, in this case just two, but we can hold how many queries we need.

Where is the trick? Future method is returning a delayed enumerable implementation, that’s all. When you iterate the enumerable (with a foreach for example), it detects and execute all the queries using a NHibernate-MultiQuery command (could be a MultiCriteria, it depends what we are using). But we don’t need to know nothing about the underlying implementation, just the concept.

In other terms, this is what happens behind the scenes:

But what if we want to retrieve an entity or a scalar ? This is too simple for an IEnumerable. Thanks to Davy Brion we have another feature called FutureValue. The mechanism is the same as Future, but instead of expect a IEnumerable, we obtain a single value (an entity or a scalar).

Note: examples adapted from Davy Brion posts [1] and [2].

Posted Fri, 30 January 2009 06:10:00 AM by darioquintana
Filed under: NH2.1, querying, HQL, Criteria, Future

comments powered by Disqus
© NHibernate Community 2024