Using named queries
Just as with SQL, mixing inline HQL with business logic is often a losing battle. The code becomes unreadable and the queries are nearly impossible to unit test properly. In this recipe, we'll show you how to move these HQL queries out of our code, improve readability and testability, and even improve performance by parsing and pre-compiling queries.
Getting ready
Complete the Getting Ready section at the beginning of this chapter.
How to do it…
Add a new folder named
NamedQueriesto the project.Add a new mapping document named
Queries.hbm.xmlwith the followingxmlcode. Don't forget to set the Build action to Embedded Resource:<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> <query name="GetBookByISBN"> <![CDATA[ from Book b where b.ISBN = :isbn ]]> </query> </hibernate-mapping>Add a new class named
NamedQueriesto the folder containing the following code:using NH4CookbookHelpers...