Using detached queries

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.

Getting ready

Complete the Getting Ready section at the beginning of this chapter.

How to do it…

  1. Add a new folder named DetachedQueries to the project.
  2. Add a new class named 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);
            }
        }
    }
  3. Run the application and start the DetachedQueries recipe.

How it works…

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.

There's more…

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

See also

  • Using CriteriaQueries
  • Using the Hibernate Query Language
  • Using named queries
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.47.166