NHibernate Redirect Object ID

I use NHibernate interceptors to log update / insert / delete information for my various objects.

Included in the registered information is the type of object and the unique identifier of the object that has been changed. The unique identifier is marked as <generator class="identity"> in the NHibernate mapping file.

The obvious problem is that when registering an Insert operation using IInterceptor.OnSave (), an object identifier has not yet been assigned.

How can I get the ID of an inserted object before recording audit information?

(I watched the PostSave event for NHibernate Listeners, but I can't get them to work with my Spring.net configuration, so I would like to stick with interceptors, if at all possible)

code:

  // object id parameter is null... public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types) { AddAuditItem(entity, INSERT); return false; } 
+4
source share
2 answers

I worked on this issue by adding a list to my interceptor class, which is populated with objects during the implementation of OnSave .

In the PostFlush implementation PostFlush list is repeated and each element is checked as an insert. The objects in this list are stored in PostFlush() and therefore have generated identifiers.

This seems to work fine, but I would appreciate it if any potential traps were pointed out :-)

 public class AuditInterceptor : EmptyInterceptor { // To hold inserted items to be audited after insert has been flushed private IList<object> insertItems = new List<object>(); public override void PostFlush(System.Collections.ICollection entities) { foreach (var entity in insertItems) { AddAuditItem(entity, INSERT); } insertItems.Clear(); base.PostFlush(entities); } public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types) { var auditable = entity as IAuditable; if (auditable != null) insertItems.Add(entity); return false; } } 
+8
source

try the OnFlushDirty method .. or maybe PostFlush

edit: also, can you post your code? Are you not getting an identifier as an OnSave parameter?

0
source

All Articles