static void

NHibernate

Simplistic "get started" code for NHibernate (version 1.2, 2 and 3).

  1. Download the latest version from NHForge.org
  2. In your data access layer, reference the NHibernate.dll
  3. Create the configuration (contains connection string).
  4. Create the domain entities. Entities are mostly POCOs but you probably should inherit from a base class for identity.
  5. Create the mapping to the database tables (in hbm.xml or use Fluent mapping)
  6. In Application Start create the session factory (don't create it for every session or operation).Simplest is to hold it in a static or singleton object such as a SessionManager.
  7. Open an ISession from the Session Factory (in asp.net you may use an IHttpModule; in MVC a global ActionFilter). Use Load/Get/SaveOrUpdate etc- then Flush/Commit to database. In asp, typically create a session with a begin request, but you could store it in Session to span requests ("conversations"). Ideally create repositories (data access objects) for each domain entity, using the SessionManager.

For quick-start database-driven NHibernate, check out my Database schema reader which has a simplistic code generator.

Example Domain

Here we just use Category and Product from Northwind.

Here are the same entities in ActiveRecord- the mapping is done by property attributes.

NHibernate helpers

NHibernate helpers - optional

Intermediate