如果事务中止,我想让NHibernate回滚事务期间保存的任何实体的标识符。我正在使用NHibernate 2.1.0,默认情况下它不会这样做。我想出了以下解决方案,它可以解决问题:
public class RevertIdentifiersEventListener : DefaultSaveEventListener
{
private class RevertIdentiferSynchronization : ISynchronization
{
private IClassMetadata _classMetadata;
private object _entity;
private object _originalIdentifier;
public RevertIdentiferSynchronization(IClassMetadata classMetadata, object entity)
{
_classMetadata = classMetadata;
_entity = entity;
_originalIdentifier = classMetadata.GetIdentifier(entity, NHibernate.EntityMode.Poco);
}
#region ISynchronization Members
public void AfterCompletion(bool success)
{
if (success == false)
{
_classMetadata.SetIdentifier(_entity, _originalIdentifier, NHibernate.EntityMode.Poco);
}
}
public void BeforeCompletion()
{
}
#endregion
}
protected override object EntityIsTransient(SaveOrUpdateEvent @event)
{
IEntityPersister entityPersister = @event.Session.GetEntityPersister(@event.EntityName, @event.Entity);
if (entityPersister.HasIdentifierProperty)
{
RevertIdentiferSynchronization revertIdentiferSynchronization = new RevertIdentiferSynchronization(entityPersister.ClassMetadata, @event.Entity);
if (@event.Session.Transaction.IsActive)
{
@event.Session.Transaction.RegisterSynchronization(revertIdentiferSynchronization);
}
}
return base.EntityIsTransient(@event);
}
}
问题在于,如果实体的保存将保存级联到关联实体,则不会回滚该实体的标识符。上面的EntityIsTransient不会为这些实体调用,只会调用显式调用Save的那些实体。
关于如何在级联时使其工作的任何建议?
答案 0 :(得分:0)
我不确定你想在什么情况下中止交易,但我假设你需要这样的事情:
using( var transaction = SessionFactory.GetSession().BeginTransaction())
{
try
{
session.Update(entity); // throws exception for some reason
}
catch(Exception ex)
{
transaction.Rollback(); // rollback the transaction
}
}