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…

  1. Add a new folder named NamedQueries to the project.
  2. Add a new mapping document named Queries.hbm.xml with the following xml 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 ...

Get NHibernate 4.x Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.