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).
tweets
Recent Posts
- How To: Configure Access Control Service on Windows Azure
- Installing Windows 8 Consumer Preview with VMWare Workstation 8
- Authorizable content with Razor
- NHibernate Validator on GitHub
- NHibernate Validator 1.3.1 GA
- NHibernate Validator 1.2 Beta3 released
- NHibernate Validator 1.2 Beta2 released
- jqGrid + Linq + Asp.Net MVC example
- Asp.net MVC: Testing a custom Authorize filters
- NHibernate Validator Quickstart
Recent Comments
- Dario on Installing Windows 8 Consumer Preview with VMWare Workstation 8
- Steve C on Installing Windows 8 Consumer Preview with VMWare Workstation 8
- Quang on StatelessSession: NHibernate without first-level cache
- Luis Fernando on NHibernate Validator 1.3.1 GA
- Daniel on NHibernate – Bulk Manipulation with SQL Native





Pingback: NHibernate Stadistics - Go Fabio Go at Dario Quintana
Pingback: Validation on NHibernate at Dario Quintana
Pingback: NHibernate EventListeners at Espacio de Dario Quintana