checking if entity (properties and collections) are dirty
I have an entity with many one-to-one relations (cascade="all-delete-orphan") and collections.
I want to check is this entity is dirty (including its collections and properties/entities from those one-t开发者_StackOverflowo-one relations), is there any way to do it?
I following this article but it doesnt cover all that I need, any help will be appreciated.
The onFlushDirty(...)
method (extends EmptyInterceptor in Hibernate) works for me to check dirty collection. The parent entity with nested collection is passed into onFlushDirty, but I was not aware that the passed-in entity could be the collection element. Once I found that, it worked both for the nested collection and its parent entity.
public class PropertyChangeInterceptor extends EmptyInterceptor{
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types)
Another method, onCollectionUpdate(...)
can also be used to catch dirty collection, it gets called after onFlushDirty(...)
.
You could use an NHibernate listener, like so:
public class AuditUpdateListener : IPostUpdateEventListener
{
private const string _noValueString = "*No Value*";
private static string getStringValueFromStateArray(object[] stateArray, int position)
{
var value = stateArray[position];
return value == null || value.ToString() == string.Empty
? _noValueString
: value.ToString();
}
public void OnPostUpdate(PostUpdateEvent @event)
{
if (@event.Entity is AuditLogEntry)
{
return;
}
var entityFullName = @event.Entity.GetType().FullName;
if (@event.OldState == null)
{
throw new ArgumentNullException("No old state available for entity type '" + entityFullName +
"'. Make sure you're loading it into Session before modifying and saving it.");
}
int[] dirtyFieldIndexes = @event.Persister.FindDirty(@event.State, @event.OldState, @event.Entity, @event.Session);
ISession session = @event.Session.GetSession(EntityMode.Poco);
string entityName = @event.Entity.GetType().Name;
string entityId = @event.Id.ToString();
foreach (int dirtyFieldIndex in dirtyFieldIndexes)
{
//For component types, check:
// @event.Persister.PropertyTypes[dirtyFieldIndex] is ComponentType
var oldValue = getStringValueFromStateArray(@event.OldState, dirtyFieldIndex);
var newValue = getStringValueFromStateArray(@event.State, dirtyFieldIndex);
if (oldValue == newValue)
{
continue;
}
// Log
session.Save(new AuditLogEntry
{
EntityShortName = entityName,
FieldName = @event.Persister.PropertyNames[dirtyFieldIndex],
EntityFullName = entityFullName,
OldValue = oldValue,
NewValue = newValue,
Username = Environment.UserName,
EntityId = entityId,
AuditEntryType = AuditEntryType.PostUpdate
});
}
session.Flush();
}
}
精彩评论