NHibernate EventListeners


In this postwe talking about StatelessSession the new feature of NHibernate 2.0.0, so another feature available at trunk (port of Hibernate too) are the EventListeners. With them we can intercept actions before or after achieve it: I.e. a Save, Update, Load, Flush and others.

At this example we gonna define the EventListener make the override from a Default base class. This could be done implementing interfaces.

public class MySaveEventListener : NHibernate.Event.Default.DefaultSaveOrUpdateEventListener
{
    protected override void CascadeBeforeSave(IEventSource source, IEntityPersister persister,
                                              object entity, object anything)
    {
        Console.WriteLine("Before Save the entity " + entity);
        base.CascadeBeforeSave(source,persister,entity,anything);
    }

    protected override void CascadeAfterSave(IEventSource source, IEntityPersister persister,
                                             object entity, object anything)
    {
        Console.WriteLine("After Save the entity " + entity);
        base.CascadeAfterSave(source,persister,entity,anything);
    }
}

The ISessionFactory programatic configuration could be done like this:

Configuration cfg = new Configuration();

cfg.Configure("hibernate.cfg.xml");

cfg.SetListener(ListenerType.Save, new MySaveEventListener());

Now we do the Save operation:

using (ISessionFactory sf = cfg.BuildSessionFactory())
{
    using (ISession session = sf.OpenSession())
    {
        Foo f1 = new Foo();
        f1.Misc = "m1";
        f1.Name = "n1";

        session.Save(f1);

        session.Flush();
    }
}

This is the console output, including the SQL generated by NHibernate:

Before Save the entity Entity Foo:0:n1
NHibernate: INSERT INTO Foo (Name, Misc) VALUES (@p0, @p1); select SCOPE_IDENTIT
Y(); @p0 = 'n1', @p1 = 'm1'
After Save the entity Entity Foo:1:n1

Foo object has it’s Integer and Identity. Before Save the Id Property has the 0 (zero) value, after Save the value was changed to 1 (because it’s the first object at base).