An NHibernate audit trail that doesn't cause “collection was not processed by flush” errors

前端 未结 4 1219
情深已故
情深已故 2020-12-31 18:14

Ayende has an article about how to implement a simple audit trail for NHibernate (here) using event handlers.

Unfortunately, as can be seen in the comments, his impl

4条回答
  •  生来不讨喜
    2020-12-31 18:42

    The fix should be the following. Create a new event listener class and derive it from NHibernate.Event.Default.DefaultFlushEventListener:

    [Serializable] 
    public class FixedDefaultFlushEventListener: DefaultFlushEventListener 
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
        protected override void PerformExecutions(IEventSource session)
        {
            if (log.IsDebugEnabled)
            {
                log.Debug("executing flush");
            }
            try
            {
                session.ConnectionManager.FlushBeginning();
                session.PersistenceContext.Flushing = true;
                session.ActionQueue.PrepareActions();
                session.ActionQueue.ExecuteActions();
            }
            catch (HibernateException exception)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("Could not synchronize database state with session", exception);
                }
                throw;
            }
            finally
            {
                session.PersistenceContext.Flushing = false;
                session.ConnectionManager.FlushEnding();
            }
    
        }
    } 
    

    Register it during NHibernate configuraiton:

    cfg.EventListeners.FlushEventListeners = new IFlushEventListener[] { new FixedDefaultFlushEventListener() };
    

    You can read more about this bug in Hibernate JIRA: https://hibernate.onjira.com/browse/HHH-2763

    The next release of NHibernate should include that fix either.

提交回复
热议问题