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.

ASP.Net MVC Book Review and musings
ASP.Net MVC musings
- ASP.Net MVC is a CoC MVC framework, it’s not a “full stack” framework. You still need to implement some type of database layer.
- Traditional ASP.net web forms attempts to hide the core parts of web development HTML, JS, CSS. ASP.Net MVC does not.
- Learning a pattern like MVC in web framework that allows developers to be aware of HTML, JS, CSS will only benefit you as a web developer.
- If you actually understand how web pages work it makes you a better debugger and a more well rounded programmer. You are able to more easily apply your knowledge and skill set to other languages/platforms. I know that some web form developers do know the details of web development, but in my opinion most do not.
- The fact that ASP.Net MVC makes it easier to test will not appeal to people who have never written a unit test in their life. You have to convince such people by showing a real world example demonstrating how test coverage can save you loads of time and money in the maintenance phase of application development. But at that point you will only get architects and project managers to buy in, the lazy developers that fear learning anything new will still avoid ASP.Net MVC like the swine flu.
- The fact that the MVC pattern is a common pattern among other web development environments such as Java and PHP will also not appeal to most Microsoft developers. However the really smart ones will realize that more common knowledge will only help if you ever have to do any type of development other than microsoft development
Book Review – Pro ASP.Net MVC Framework – Steven Sanderson

Book on Amazon I am a Java, PHP, and .Net developer which may make my opinion worthless to some Microsoft zealots but I thought I would type up my thoughts on this book anyway. Overall I found this book to be a great way to learn ASP.Net MVC. It has great examples and enough background material to bring people new to the MVC pattern up to speed. Below are my pros and cons along with notes on chapters 1-13.
Note about the cover.
One thing I found interesting is that the cover says “Discover the biggest innovation in Microsoft web development since asp.net 1.0″. I find it amusing that something as old as MVC web frameworks can be called an innovation for asp.net development since MVC frameworks are nothing new to web development. Heck they are not even new to ASP.Net development. See MonoRail .
Pros
- Provides good definition of MVC and explains why you want to use it
- Overall all the examples are clear and concise
- Gives examples of how to test every part of ASP.Net MVC
- Moves quick enough for someone with MVC experience and slow enough for someone with no MVC experience
- Great chapter on web site security
- Book often demonstrates C# 3 language features
Cons
- Database examples use LINQ to SQL.
- As many have noted this isn’t a major con. It was probably used to keep the examples shorter. Whether you like LINQ to SQL or not that is a good thing.
- No mention of Mono project or any hints of how to get ASP.Net working with Mono.
- Book examples are for the “real” version of VS2008 not the free VWDE2008.
- Does not provide a good example of using a validation utility such as XVal or Data Annotations
Chapter 1
- An adequate history lesson for those unfamiliar with MVC.
Chapter 2
- A great chapter that quickly and easily shows you the basics of ASP.Net MVC
Chapter 3
- Gives in depth definition to each part of MVC
- Gives good definition of entities vs value objects
- Lists design and pattern best practices
- Brief discussion of IoC and IoC containers
- Brief discussion on automated testing and the TDD movement
- Gives example of creating mock implementations for testing
Chapter 4
- Goes into medium depth while building a project with unit testing, domain model, and web layer
- uses LING to SQL for database interactions
- Sets up IoC with Castle Windsor
- Shows how to use Nunit and Moq to create unit tests
- Good definition of TDD and how the author thinks of it as actually BDD (behaviour driven development)
Chapter 5
- Examples of how to test every part of ASP.Net MVC
- Shows example of how to only expose an interface in your controller to avoid tying the controller to your business logic implementation
Chapter 6
- CRuD actions and views are added to the example project
- Example of username/password authentication
- Shows how to upload an image through a form field
Chapter 7
- Detail of asp.net MVC project folder structure
- Very well done, explains the what/why for each folder
- Goes over the naming convention which are crucial since ASP.Net MVC follows CoC
Chapter 8
- Everything you need to know about how url routing works and also how to create links in your application to your controllers/actions
Chapter 9
- More details on what code belongs in a controller/action
- More details on how the views are rendered
- Example of how to use the [Authorize] filter attribute, which is a great way to easily secure your actions individually
Chapter 10
- Details on how views work specifically how data is passed between layers and tools available to display that data. Specifically the HTML helpers.
Chapter 11
- Everything you need to know about how to modify and configure how data is retrieved from forms and urls and then binded to action parameters and model objects
- Validation
- Author basically suggest using plain c# in the model layer for validation. doesn’t list the re-usability and “all ready done for YOu” benefits of using a validation utility.
Chapter 12
- Simple examples of how to use the AJAX HTML helpers which includes JQuery.
Chapter 13
- Demonstrates basics of HTTP requests to help you understand how vulnerable web sites are. Really good reading for less experienced web developers.
- Gives example of how to fake an http request
- Gives examples of using tools like firebug and fiddler
- Details cross-site scripting and html injection
- Details how one of the previous chapter examples had a vulnerability and how it can be fixed
