NHibernate 2 Beginner’s Guide – Book Review
Finally someone has written an in depth beginners book for nhibernate. Nhibernate 2.0 Beginners Guide written by Aaron Cure is just that and more. Wow do I sound like a car salesman. I was a little disappointed when I read Nhibernate In Action last year, because it was more of a reference than a tutorial. This book is definitely what the title states, which is a beginners guide. The book contains step by step examples of how to find, setup, and use nhibernate. I highly recommend this book to anyone wanting to learn nhibernate. By the way I think all .netters should do just that.
Pros
- love the beginning paragraphs
- In simple terms, NHibernate does all the database work, and we reap all the benefits! Instead of writing reams of SQL statements or creating stored procedures that “live” in a different place than our code, we can have all of our data access logic contained within our application.
With a few simple “tricks” that we’ll discuss in Chapter 4, Data Cartography, not only will our queries be effective, but they will also be validated by the compiler. Therefore, if our underlying table structure changes, the compiler will alert us that we need to change our queries!
- In simple terms, NHibernate does all the database work, and we reap all the benefits! Instead of writing reams of SQL statements or creating stored procedures that “live” in a different place than our code, we can have all of our data access logic contained within our application.
- starts slow, which is perfect for a “beginners” book. lots of hand holding and explanations of basics. this is truly meant for somehow with no experience with ORMs.
- clearly shows you how to use log4net! great bonus in a nhibernate book.
- briefly mentions all the major players in the nhibernate world, which is great for demonstrating options
- Examples: fluent nhibernate, nhibernate.burrow, castle, spring ioc, etc.
Cons
- book uses basic aspx pages with custom controls in the examples. I firmly suggest ASP.Net MVC over webforms. But it may be too much to learn at one time if you aren’t familiar with either nhib or MVC. So learn one first and then learn the other. You won’t regret it.
- most examples are in c# and vb.net. that’s good or bad depending on your opinion of vb.net.
- No HQL examples. All query examples use the Criteria class. This isn’t totally bad especially for beginners, but HQL should have at least been mentioned.
Chapter Notes
- chapter 1
- clearly denotes which version of nhib the book uses and where to get it
- Even explains the nhib release verbiage of “generally available”
- shows basic examples of mapping file and how it relates to POCOs. Good stuff for a ORM newbie.
- clearly denotes which version of nhib the book uses and where to get it
- chapter 2
- good advice for designing your database in logical way that avoids data duplication.
- clear steps to download and setup a database using sql server express
- Does mention that nhib works in almost any database, however all the book examples use sql server express
- nice explanation of how tables relate to your classes
- great introduction to OTM, MTO, MTM, and OTO relationships
- good summary of left joins and how joins matter in queries for the different relationship types
- chapter 3
- starts creating a simple class library application. clear steps and good examples.
- even addresses the somewhat hated nullable types and how to handle database columns that need to be mapped to types that can be null.
- chapter 4
- nice explanation of what mapping means in terms of ORM software and how it functions as the glue that binds your objects to the database.
- summary and examples of the most common used mapping types
- gives examples of two mapping styles
- xml
- lists the two main complaints which are.. 1) too much xml 2) xml files are not compiled, so you don’t find bugs until run time.
- provides great tip of adding the hibernate XSD to your project so that visual studio will provide code completion for you and validate your mapping files.
- important info about how to make sure the xml mapping files are compiled into your dll
- fluent nhibernate
- short example given that shows how using the “side” project http://fluentnhibernate.org/ can work without the xml mapping files.
- pro is that mappings have to be compiled, so bugs/typos are found earlier
- xml
- chapter 5
- creates console application to test the nhib code
- shows step by step how to add references to the nhib dlls that you need to download
- good definition of what a nhib session is and how it relates to an actual database session
- chapter 6
- why you should and how to use log4net with your nhib project
- excellent and thorough tutorial for using log4net
- chapter 7
- nhib config details
- mentions how easy it is to change databases by simply changing one config line
- shows how to config nhib in an app.config or web.config
- chapter 8
- provides example of Singleton DOA pattern
- shows example of using a structure that holds all the column/property names for a class/entity. this is done so that the column names in the structure can be used in criteria queries. all this effort is done to avoid run time exceptions. seems like a waste of time to me because you if you don’t update your structure every time your db is updated then you will still get runtime errors.
- query examples using Criteria (at this point all examples have been using Criteria, none in HQL)
- chapter 9
- in depth examples showing how to create custom controls to display data retrieved using nhibernate
- chapter 10
- shows how to implement the login controls with nhibernate
- chapter 11
- covers 11 code generation tools used to limit manual boiler plate coding. I actually hadn’t heard of many of the ones listed. Great bonus chapter.
- nhib-gen, mygeneration, NGen NHibernate Code Generator, and T4 hbm2net seem promising
- these tools create everything from POCOs to DAOs to services.
NHibernate in Action – Book Review

Book on Amazon
All summer I meant to read the book “NHibernate In Action”. I finally got around to it, better late than never I guess. In my opinion this book is aimed at higher level programmers such as lead developers or architects. The book does not contain clear step by step examples of how to get NHibernate running. However it does provide in depth conceptual reasoning why anyone would want to use NHibernate along with reference style examples. If you are trying to learn NHibernate you are better off reading a few online tutorials first and after that read this book so you can understand exactly what NHibernate is doing and how it does it. Below are some book pros & cons, NHibernate links, and chapter summaries.
Pros
- Examples are all in c#
- Shows config examples for NHibernate 1.2.1 and 2
- Promotes proper design patters often references popular pattern books
- Makes note of minor current bugs or missing features that may cause issues or confusion
- Provides suggestions for when to use something other than the default NHibernate settings
- Mentions how NHibernate can use the features of multiple RDMS, not just SQL Server
Cons
- Download and install instructions were vague
- I downloaded NHibernate 2.1.0 QA from SourceForge after finally finding the link on nhforge.org. From there I followed the install notes in the downloaded zip file.
- Examples do not use Generics
- Doesn’t provide a link or even a suggestion to where you can download the NHibernate.Mapping.Attributes library which lets you use features similar to the annotations in Hibernate 3
- I found them here: http://sourceforge.net/projects/nhcontrib/files/NHibernate.Mapping.Attributes/
- Shows attribute and xml mapping examples randomly. In my opinion it would be better if one or the other was used consistently.
- Jumps from definitions to examples. No clear step by step examples
- I would say this book is more of a reference than tutorial
Helpful NHibernate Links
- NHibernate community site
- NHibernate Google Group
- Stackoverflow NHibernate questions and answers
- How to use MySQL with .NET
- Databases supported by NHibernate
- Common exceptions
Chapter 1
- Basic definitions of persistence, sql(sql not sql server) databases, and layered development
- Doesn’t mention the testability benefits of layered development
- Compares persistence layer choices available with .Net
- Makes the case that LINQ and Entity framework will not replace NHibernate
- Definition of ORM
- Addresses the performance concerns of using ORMs
- Author tries to convince people to use ORMs, this part needs a little salesman ship but I guess if someone is open minded enough to read this book then they don’t need much of a sales pitch.
Chapter 2
- Some basoc instructions for how to download and install the NHibernate dll
- con: Could use a little details in this section about how to use the versions that don’t have msi installers yet like the 2.1.0.GA release I downloaded.
- Shows very simple examples of saving and loading an entity
- Then shows you a basic xml mapping document
- o Shows a mapping document for versions 1.2 and 2.
- Quick glance at the NHibernate api and in depth notes on important interfaces
- Very short section on logging with log4net
Chapter 3
- Good section on the benefits of having a transparent persistence layer
- Discusses the anti xml config file movement.
- However doesn’t mention the fact that poorly designed and overly complicated schemas are one reason for the back lash. Also never mentions CoC.
- Discusses using attributes as meta data
- IMHO way more time should have been spent telling the users how to setup/install the mapping dlls needed to use this feature
- Does show many examples of how to use the attributes and what the xml version of the meta data would look like
- This chapter provides information about the hibernate mapping elements and options
- It is a mix between a reference and tutorial.
- Good section on object identity vs equality
- con: Gives an explanation of what primary keys are. Surely anyone reading this book knows already knows what primary keys are.
- Good short explanation of the different types of primary key creation that NHibernate supports
- Long discussion on database and object model design
- table per concrete class
- table per sub class
- table per class hierarchy
Chapter 4
- Explains object identity scope. probably a little high level for low level developers
- Explains different options for Equals and HashCode implementations
- Automatic dirty checking
- Changing an object in an ISession and committing will result in those changes being automatically reflected in the database
- Clearly denotes the different cascading persistence options
- Details the different object retrieval options
- Retrieving by identifier
- HQL
- NHibernate Criteria API
- Native SQL queries
- In depth discussion of fetching strategies and how to implement each one
- Short section on batching and how it can speed up queries for selecting collections
- Provides common sense ideas for analyzing NHibernate’s performance
Chapter 5
- Background on database transactions, unit of work and conversations
- Excellent section on transaction isolation
- Background on ORM caching
Chapter 6
- Starts with more definitions and comparisons of entities and value types
- Nice chart showing how NHibernate mapping types relate to .Net types
- Give in depth example of creating a custom mapping type
- Nice tips on controlling collection sorting with mapping settings
Configuring NHibernate in a Multiple Project Layout
I recently had to setup NHibernate in a multiple project c#, asp.net MVC solution. Since most of the tutorials and books only show a basic single project layout I thought I would post an example of how to configure NHiberate with a multi-project solution.
The main problem I had was that my model objects or entity objects were in a separate project than my database access code which contained the .hbm.xml mapping files. When I tried to configure NHibernate with the basic examples I was getting an “NHibernate.MappingException : No persister for: YourClass” exception. I was still getting that exception even after changing the .hbm.xml files to be an “Embedded Resource”. I finally figured out that my .hbm.xml files needed to reference the ModelLayer assebmly and my NHibernate.Cfg.Configuration.AddAssembly() needed to reference the DataAccessLayer assebmly. See screen shots and code examples below for more details.
Solution layout
- DataAccessLayer
- Duh. Database code
- References
- ModelLayer
- ModelLayer
- Model objects
- MvcAgain (web layer)
- ASP.Net project
- References
- ModelLayer
- ServiceLayer
- ServiceLayer
- Business logic
- Reusable logic
- References
- ModelLayer
- DataAccessLayer
Model objects Car.cs and CarLot.cs
using System.ComponentModel.DataAnnotations;
namespace MvcAgain.Models {
public class Car {
[Required]
public virtual int Id {get; set;}
[StringLength(35), Required]
public virtual string Manufacturer {get; set;}
[StringLength(35), Required]
public virtual string Model {get; set;}
public virtual CarLot Lot {get; set;}
}
}//end of Car.cs
using Iesi.Collections;
using System.ComponentModel.DataAnnotations;
namespace MvcAgain.Models {
public class CarLot {
[Required]
public virtual int Id { get; protected set; }
[StringLength(35), Required]
public virtual string Name { get; protected set; }
public virtual ISet Cars { get; protected set; }
}
}//end of CarLot.cs
Car.hbm.xml and CarLot.hbm.xml
These .hbm.xml files are in the DataAccessLayer project, but they reference the ModelLayer assembly.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="ModelLayer"
namespace="MvcAgain.Models">
<class name="MvcAgain.Models.Car" lazy="false" table="cars">
<id name="Id">
<generator class="native"/>
</id>
<property name="Model"/>
<property name="Manufacturer"/>
<many-to-one name="Lot" class="CarLot" column="lotid" not-null="true">
</many-to-one>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="ModelLayer"
namespace="MvcAgain.Models">
<class name="MvcAgain.Models.CarLot" lazy="false" table="carlots">
<id name="Id">
<generator class="native"/>
</id>
<property name="Name"/>
<set name="Cars" inverse="true">
<key column="lotid"/>
<one-to-many class="Car"/>
</set>
</class>
</hibernate-mapping>
NHibernateSessionFactory.cs (NHibernate configuration code)
using NHibernate.Cfg;
using NHibernate;
namespace MvcAgain.DataAccessLayer {
public class NHibernateSessionFactory {
private static ISessionFactory sessionFactory = null;
private static ISessionFactory SessionFactory {
get {
if(sessionFactory == null) {
Configuration configuration = new Configuration();
configuration.Configure();
//note: you must use the name of the assembly
//that contains the .hbm.xml mapping files.
//For this example NHibernate will load all .hbm.xml files it
//finds in the DataAccessLayer assembly
configuration.AddAssembly("DataAccessLayer");
sessionFactory = configuration.BuildSessionFactory();
}
return sessionFactory;
}
}
public static ISession OpenSession() {
return SessionFactory.OpenSession();
}
}//end of class
}//end of namespace
ModelLayer assembly name in the properties pane.

