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.
Add a new folder named
NamedQueries
to the project.Add a new mapping document named
Queries.hbm.xml
with the followingxml
code. 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
NamedQueries
to the folder containing the following code:using NH4CookbookHelpers...