In some cases, it may be preferable to build an HQL or criteria query object in parts of your application without access to the NHibernate session and then execute them elsewhere with a session available. In this recipe, we'll show you how to use detached queries and criteria.
DetachedQueries
to the project.Recipe
to the folder:using NH4CookbookHelpers.Queries; using NH4CookbookHelpers.Queries.Model; using NHibernate; using NHibernate.Criterion; namespace QueryRecipes.DetachedQueries { public class Recipe : QueryRecipe { protected override void Run(ISession session) { var isbn = "3043"; var query = DetachedCriteria.For<Book>() .Add(Restrictions.Eq("ISBN", isbn)); var book = query.GetExecutableCriteria(session) .UniqueResult<Book>(); Show("Book with ISBN=3043",book); } } }
DetachedQueries
recipe.In this recipe, we've used a DetachedCriteria
object from the NHibernate.Criterion
namespace. This allows us to set up our query without an active session. Later, inside a transaction, we call GetExecutableCriteria
to return an ICriteria
associated with the session. Finally, we call UniqueResult
to return the book.
NHibernate also provides DetachedQuery
and DetachedNamedQuery
in the NHibernate.Impl
namespace for detached HQL queries. The code is given as follows:
var query = new DetachedNamedQuery("GetBookByISBN") .SetString("isbn", isbn); var query = new DetachedQuery(hql) .SetString("isbn", isbn);
Detached criteria and queries implement the query objects pattern shown on Martin Fowler's website at http://martinfowler.com/eaaCatalog/queryObject.html
3.137.163.208