About This Book – NHibernate in Action

About This Book

The NHibernate project was started back in 2003 by Paul Hatcher, and with the tremendous work done by Mike Doerfler and Sergei Koshcheyev, it has steadily become a mature product, popular with thousands of .NET developers.

NHibernate was originally a port of the incredibly popular Java Hibernate project, and object/relational mapping has been very popular with the Java crowd for many years.

A consequence of this popularity is that Java developers have access to a whole heap of books about Hibernate. In fact, the last time I counted I found 15 books dedicated purely to this single tool. New books on Hibernate and related technologies are still appearing regularly.

Until now, .NET developers have had no such luxury for learning NHibernate. This book aims to remedy that problem—we finally have our “manual” written for .NET developers and focusing solely on NHibernate. NHibernate in Action is based on the best-selling Hibernate in Action, which is considered to be the de facto manual for Java Hibernate. The book is much more than a translation; in fact, much work has gone into making it appeal to the .NET developer while also accommodating API changes, code differences, new features, and the like.

We hope that the arrival of this book is considered good timing. The world of .NET is finally getting excited about object/relational mapping, and we hope this book will help you discover, learn, and enjoy one of the most mature, powerful ORM frameworks available.

Who should read this book

This book is written for developers who work with Microsoft .NET. Both developers and architects should be able to draw great value from this book, regardless of whether they’re new to NHibernate and ORM or they’ve already gained some experience with it.

For those new to NHibernate, this book assumes no prior knowledge. We also don’t expect that you’ve worked with any object/relational mapping framework before. The idea is that that you can take the knowledge in this book and start building NHibernate solutions with it.

We also anticipate that many reading this book might have used NHibernate on a few projects already, either on its own or as part of another library such as Castle Active Record or Spring.NET. This book will help you if you want to learn a little more about what’s going on behind the scenes. It will also help you leverage the great features of NHibernate and understand how to take full advantage of them.

We’ve done our best to give as much background detail as possible on both the common and the not-so-common usages of NHibernate. We’ve covered many topics that are barely mentioned in forums and blogs, such as the persistence lifecycle and some of the more exotic mapping capabilities.

Regardless of whether you’re new to NHibernate or a seasoned user, we hope this book will teach you new things and increase your enjoyment and success with the tool.


Chapter 1 sets the scene, explaining what persistence is and how it fits into business applications. We take a glimpse at NHibernate, comparing it to other popular approaches such as LINQ to SQL and DataSets. You’ll then learn about the fundamental problems posed in object/relational mapping and how NHibernate tackles them.

Chapter 2 puts some code under your nose! Our brief tour takes you from installing NHibernate to building and running a simple application. We then go on to explore the main facilities available in NHibernate, including the APIs for querying, transactions, and customization. We round off with both basic and advanced configuration techniques and show how you can use logging to get a deeper insight into how NHibernate operates behind the scenes.

Chapter 3 will bring you up to speed with the bulk of NHibernate’s capabilities. We take a more sophisticated problem—the CaveatEmptor application—and guide you through modeling your domain model, along with mapping it using various types of associations. You’ll learn how NHibernate allows mapping with XML and the .NET attributes. We also explain some smarter capabilities, such as flexible property mappings and automatic naming conventions. The chapter also explains the importance of identity in ORM, before building on previous knowledge by explaining more about mapping inheritance and associations.

Chapter 4 gives further insight into some important concepts: entity lifecycle, persistent states, and equality. We look at how this knowledge can be leveraged by NHibernate’s APIs. We also look at working with entire object graphs, discussing cascading persistence, batching, lazy fetching, and eager fetching.

Chapter 5 delves into using NHibernate to get tight control over database transactions. We then discuss long-running business transactions and demonstrate how to achieve automatic versioning and locking. Caching is core to NHibernate, and you’ll learn a great deal here about the first- and second-level caches.

Chapter 6 introduces the NHibernate type system and how to implement custom user types. We move on to discuss components, value types, and working with the more advanced associations, indicating some best practices when working with them.

Chapter 7 focuses on efficiently querying NHibernate. We examine both HQL and the ICriteria API, giving many code samples for each. You’ll see glorious detail for parameter binding, named queries, polymorphic queries, and joins. We also look at how you can run efficient report queries, use collection filters, and use plain SQL rather than HQL. Finally, this chapter looks at solving common performance problems, discussing the n+1 selects problem and caching.

Chapter 8 offers a look at patterns and practices around NHibernate. We give example code for common practices such as layered applications and unit testing. Also included are some helpful tips for finding bugs in your applications. We also give an example implementation of adding additional services to NHibernate applications, such as audit logging.

Chapter 9 starts by discussing development processes and available tools, explaining the various starting points for an NHibernate application. We also look at code generation and automatic schema maintenance, for evolving domain models and databases in tandem. We then look at working with legacy databases and explain some tried and tested tricks for dealing with things like composite keys and triggers.

Chapter 10 gives more real-world knowledge. We look at refactoring a sample application into layers, with a well-defined persistence layer and a smart domain model. This chapter also introduces the DAO pattern with generics, and a useful NHibernate Helper class. Finally, we look at session management for web applications, implementing long-running business conversations, and demonstrating how to implement distributed transactions.

Code conventions and downloads

All source code in listings or in text is in a fixed-width font like this to separate it from ordinary text. Code annotations accompany many of the listings, highlighting important concepts. In some cases, numbered bullets link to explanations that follow the listing.

The complete example code for the book can be downloaded from the Manning web site at www.manning.com/kuate or www.manning.com/NHibernateinAction.

Author Online

Purchase of NHibernate in Action includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the lead author and from other users. To access the forum and subscribe to it, point your web browser to www.manning.com/NHibernateinAction or www.manning.com/kuate. This page provides information on how to get on the forum once you’re registered, what kind of help is available, and the rules of conduct on the forum.

Manning’s commitment to our readers is to provide a venue where a meaningful dialog between individual readers and between readers and the authors can take place. It’s not a commitment to any specific amount of participation on the part of the authors, whose contribution to the AO remains voluntary (and unpaid). We suggest you try asking the authors some challenging questions lest their interest stray!

The Author Online forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.

About the authors

PIERRE HENRI KUATÉ is one of the main developers on the NHibernate project team, author of the NHibernate.Mapping.Attributes library, and a major contributor to the NHibernate forum. He was responsible for managing the NHibernate documentation, website, and forum on the Hibernate.org site. He started using NHibernate more than four years ago in commercial development.

TOBIN HARRIS has worked with NHibernate since it was in early beta. He’s passionate about tools and practices that help build quality software at high speeds. As an independent consultant and entrepreneur, Tobin works with companies across the globe in various sectors including banking, personal finance, healthcare, software components, and new media. Tobin obtained his degree in software engineering at Leeds Metropolitan University and continues to work and live in Leeds, UK.

CHRISTIAN BAUER is a member of the Hibernate developer team and a trainer, consultant, and product manager for Hibernate, EJB 3.0, and JBoss Seam at JBoss. He is the lead author of Manning’s Hibernate in Action and Java Persistence with Hibernate.

GAVIN KING is a lead developer at JBoss, the creator of Hibernate, and a member of the EJB 3.0 (JSR 220) expert group. He also leads Web Beans JSR 299, a standardization effort involving Hibernate concepts, JSF, and EJB 3.0, and is coauthor with Christian of the two books mentioned above.

About the title

By combining introductions, overviews, and how-to examples, the In Action books are designed to help learning and remembering. According to research in cognitive science, the things people remember are things they discover during self-motivated exploration.

Although no one at Manning is a cognitive scientist, we are convinced that for learning to become permanent it must pass through stages of exploration, play, and, interestingly, retelling of what is being learned. People understand and remember new things, which is to say they master them, only after actively exploring them. Humans learn in action. An essential part of an In Action guide is that it’s example-driven. It encourages the reader to try things out, to play with new code, and explore new ideas.

There is another, more mundane, reason for the title of this book: our readers are busy. They use books to do a job or solve a problem. They need books that allow them to jump in and jump out easily and learn just what they want just when they want it. They need books that aid them in action. The books in this series are designed for such readers.

About the cover illustration

The figure on the cover of NHibernate in Action is taken from the 1805 edition of Sylvain Maréchal’s four-volume compendium of regional dress customs. This book was first published in Paris in 1788, one year before the French Revolution. Each illustration is finely drawn and colored by hand.

The colorful variety of Maréchal’s collection reminds us vividly of how culturally apart the world’s towns and regions were just 200 years ago. Isolated from each other, people spoke different dialects and languages. In the streets or the countryside, they were easy to place—sometimes with an error of no more than a dozen miles—just by their dress.

Dress codes have changed everywhere with time and the diversity by region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants of different continents, let alone different towns or regions. Perhaps we have traded cultural diversity for a more varied personal life—certainly for a more varied and fast-paced technological life.

At a time when it is hard to tell one computer book from another, Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by Maréchal’s pictures.