Chapter 4. Persistent Classes

Persistent classes are classes in an application that implement the entities of the business problem (e.g. Customer and Order in an E-commerce application). Persistent classes have, as the name implies, transient and also persistent instance stored in the database.

NHibernate works best if these classes follow some simple rules, also known as the Plain Old CLR Object (POCO) programming model.

4.1. A simple POCO example

Most .NET applications require a persistent class representing felines.

using System;
using Iesi.Collections;

namespace Eg
{
    public class Cat
    {
        private long id; // identifier
        private string name;
        private DateTime birthdate;
        private Cat mate;
        private ISet kittens
        private Color color;
        private char sex;
        private float weight;
    
        public virtual long Id
        {
            get { return id; }
            set { id = value; }
        }
    
        public virtual string Name
        {
            get { return name; }
            set { name = value; }
        }
    
        public virtual Cat Mate
        {
            get { return mate; }
            set { mate = value; }
        }
    
        public virtual DateTime Birthdate
        {
            get { return birthdate; }
            set { birthdate = value; }
        }
    
        public virtual float Weight
        {
            get { return weight; }
            set { weight = value; }
        }
    
        public virtual Color Color
        {
            get { return color; }
            set { color = value; }
        }
    
        public virtual ISet Kittens
        {
            get { return kittens; }
            set { kittens = value; }
        }
    
        // AddKitten not needed by NHibernate
        public virtual void AddKitten(Cat kitten)
        {
            kittens.Add(kitten);
        }
    
        public virtual char Sex
        {
            get { return sex; }
            set { sex = value; }
        }
    }
}

There are four main rules to follow here:

4.1.1. Declare accessors and mutators for persistent fields

Cat declares accessor methods for all its persistent fields. Many other ORM tools directly persist instance variables. We believe it is far better to decouple this implementation detail from the persistence mechanism. NHibernate persists properties, using their getter and setter methods.

Properties need not be declared public - NHibernate can persist a property with an internal, protected, protected internal or private visibility.

4.1.2. Implement a default constructor

Cat has an implicit default (no-argument) constructor. All persistent classes must have a default constructor (which may be non-public) so NHibernate can instantiate them using Activator.CreateInstance().

4.1.3. Provide an identifier property (optional)

Cat has a property called Id. This property holds the primary key column of a database table. The property might have been called anything, and its type might have been any primitive type, string or System.DateTime. (If your legacy database table has composite keys, you can even use a user-defined class with properties of these types - see the section on composite identifiers below.)

The identifier property is optional. You can leave it off and let NHibernate keep track of object identifiers internally. However, for many applications it is still a good (and very popular) design decision.

What's more, some functionality is available only to classes which declare an identifier property:

  • Cascaded updates (see "Lifecycle Objects")

  • ISession.SaveOrUpdate()

We recommend you declare consistently-named identifier properties on persistent classes.

4.1.4. Prefer non-sealed classes and virtual methods (optional)

A central feature of NHibernate, proxies, depends upon the persistent class being non-sealed and all its public methods, properties and events declared as virtual. Another possibility is for the class to implement an interface that declares all public members.

You can persist sealed classes that do not implement an interface and don't have virtual members with NHibernate, but you won't be able to use proxies - which will limit your options for performance tuning.

4.2. Implementing inheritance

A subclass must also observe the first and second rules. It inherits its identifier property from Cat.

using System;
namespace Eg
{
    public class DomesticCat : Cat
    {
        private string name;

        public virtual string Name
        {
            get { return name; }
            set { name = value; }
        }
    }
}

4.3. Implementing Equals() and GetHashCode()

You have to override the Equals() and GetHashCode() methods if you intend to mix objects of persistent classes (e.g. in an ISet).

This only applies if these objects are loaded in two different ISessions, as NHibernate only guarantees identity ( a == b , the default implementation of Equals()) inside a single ISession!

Even if both objecs a and b are the same database row (they have the same primary key value as their identifier), we can't guarantee that they are the same object instance outside of a particular ISession context.

The most obvious way is to implement Equals()/GetHashCode() by comparing the identifier value of both objects. If the value is the same, both must be the same database row, they are therefore equal (if both are added to an ISet, we will only have one element in the ISet). Unfortunately, we can't use that approach. NHibernate will only assign identifier values to objects that are persistent, a newly created instance will not have any identifier value! We recommend implementing Equals() and GetHashCode() using Business key equality.

Business key equality means that the Equals() method compares only the properties that form the business key, a key that would identify our instance in the real world (a natural candidate key):

public class Cat
{

    ...
    public override bool Equals(object other)
    {
        if (this == other) return true;
        
        Cat cat = other as Cat;
        if (cat == null) return false; // null or not a cat

        if (Name != cat.Name) return false;
        if (!Birthday.Equals(cat.Birthday)) return false;

        return true;
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int result;
            result = Name.GetHashCode();
            result = 29 * result + Birthday.GetHashCode();
            return result;
        }
    }

}

Keep in mind that our candidate key (in this case a composite of name and birthday) has to be only valid for a particular comparison operation (maybe even only in a single use case). We don't need the stability criteria we usually apply to a real primary key!

4.4. Lifecycle Callbacks

Optionally, a persistent class might implement the interface ILifecycle which provides some callbacks that allow the persistent object to perform necessary initialization/cleanup after save or load and before deletion or update.

The NHibernate IInterceptor offers a less intrusive alternative, however.

public interface ILifecycle
{                                                                    (1)
        LifecycleVeto OnSave(ISession s);                            (2)
        LifecycleVeto OnUpdate(ISession s);                          (3)
        LifecycleVeto OnDelete(ISession s);                          (4)
        void OnLoad(ISession s, object id);
}
(1)

OnSave - called just before the object is saved or inserted

(2)

OnUpdate - called just before an object is updated (when the object is passed to ISession.Update())

(3)

OnDelete - called just before an object is deleted

(4)

OnLoad - called just after an object is loaded

OnSave(), OnDelete() and OnUpdate() may be used to cascade saves and deletions of dependent objects. This is an alternative to declaring cascaded operations in the mapping file. OnLoad() may be used to initialize transient properties of the object from its persistent state. It may not be used to load dependent objects since the ISession interface may not be invoked from inside this method. A further intended usage of OnLoad(), OnSave() and OnUpdate() is to store a reference to the current ISession for later use.

Note that OnUpdate() is not called every time the object's persistent state is updated. It is called only when a transient object is passed to ISession.Update().

If OnSave(), OnUpdate() or OnDelete() return LifecycleVeto.Veto, the operation is silently vetoed. If a CallbackException is thrown, the operation is vetoed and the exception is passed back to the application.

Note that OnSave() is called after an identifier is assigned to the object, except when native key generation is used.

4.5. IValidatable callback

If the persistent class needs to check invariants before its state is persisted, it may implement the following interface:

public interface IValidatable
{
        void Validate();
}

The object should throw a ValidationFailure if an invariant was violated. An instance of Validatable should not change its state from inside Validate().

Unlike the callback methods of the ILifecycle interface, Validate() might be called at unpredictable times. The application should not rely upon calls to Validate() for business functionality.