简体   繁体   中英

can you have multiple transactions occur inside one session in nhibernate? And is it a bad idea?

I'm thinking about making my own IUnitOfWork implementation for an NHibernate persistence layer.

It seems that the right way to do this would be to have the ISession and the ITransaction instantiated in the constructor, and then disposed in the destructor or the Dispose() method.

Of course, if someone invokes the Save() method, then the ISession would be flushed and the ITransaction would be complete, so after calling Save() , there would not be a valid open transaction to Save() again... unless I committed the first transaction and immediately opened another, new transaction. But is this a good idea?

Design-wise, it makes sense to do one commit operation, but I will not necessarily have control of the code and other developers may be less disciplined about following the UnitOfWork pattern.

Do I lose/ gain anything by trying to make the UnitOfWork tolerant to multiple transactions per session? Should I just check for an open transaction and throw an exception if it's already been committed, rather than making a new transaction?

To answer the first question: yes it is possible to have multiple transactions in one session.

Is is a good idea? It depends.

The problem is that changing data in the first transaction would be committed, while it is not sure if the whole unit of work (session) gets committed at the end. When you get, let's say, a StaleObjectException in a later transaction, you already had some data committed. Note that this kind of exception makes your session unusable and you had to destroy it anyway. Then it is hard to start over and try again.

I would say, it works well under these circumstances:

  • It is a UI application
  • Changes are only flushed in the last transaction.

UI Application

Errors are handled by the user interactively. This means that the user can see what's actually stored in a case of error and repeats the changes he made.

Changes are only flushed in the last transaction

The session as implemented by NH only flushes changes at the end or "when necessary". So it would be possible to keep changes in memory until the session gets committed. The problem is that NH needs to flush the session before every query, which is hard to control. It can be turned off, which leads to side effects. When writing simple transactions, you may have it under control. In a complex system it's virtually impossible to make sure that nothing is going wrong.

The Simple Way (tm)

I wrote the persistence layer of a quite large client-server system. In such a system, you don't have a user handling errors directly. You need to handle the errors in the system and return control to the client in a consistent state.

I simplified the whole transaction handling to an absolute minimum, in order to make it stable and "idiot proof". I have always a session and a transaction created together and it gets either committed or not.

There are multiple option available to implement nhibernate nested transaction with unit of work.

Here I am using Command pattern for unit of work.

public interface IAction
{    
    void Execute();
}

public abstract class Action<T> : IAction, IDisposable where T : Action<T>
{
    public void Execute()
    {
        try
        {
            //Start unit of work  by your unit of work pattern or
            transaction.Begin();
            OnExecute();
            //End Unit of work
            transaction.Commit();
        }
        catch (Exception e)
        {
            transaction.Rollback();
            throw e;
        }
    }

    protected abstract void OnExecute();

    public void Dispose()
    {

    }
}

public class MyBusinessLogic : Action<MyBusinessLogic>
{
    protected override void OnExecute()
    {
       //Implementation
    }
}

public class MyAnotherBusinessLogic : Action<MyAnotherBusinessLogic>
{
    protected override void OnExecute()
    {
        //Nested transaction
        MyBusinessLogic logic = new MyBusinessLogic();
        logic.Execute();
    }
}

I think that the solution with one transaction per unit of work is too restrictive. In some environments one can need the ability to perform several transactions per session. I myself manage the transactions explicitly and it seems to be a flexible solution.

public interface IUnitOfWork: IDisposable
{
    IGenericTransaction BeginTransaction();
}

public interface IGenericTransaction: IDisposable
{
    void Commit();

    void Rollback();
}

public class NhUnitOfWork: IUnitOfWork
{
    private readonly ISession _session;

    public ISession Session
    {
        get { return _session; }
    }

    public NhUnitOfWork(ISession session)
    {
        _session = session;
    }

    public IGenericTransaction BeginTransaction()
    {
        return new NhTransaction(_session.BeginTransaction());
    }

    public void Dispose()
    {
        _session.Dispose();
    }
}

public class NhTransaction: IGenericTransaction
{
    private readonly ITransaction _transaction;

    public NhTransaction(ITransaction transaction)
    {
        _transaction = transaction;
    }

    public void Commit()
    {
        _transaction.Commit();
    }

    public void Rollback()
    {
        _transaction.Rollback();
    }

    public void Dispose()
    {
        _transaction.Dispose();
    }
}

The usage looks like this. It is easily incorporated into any pattern.

public void Do(IUnitOfWork uow)
{
  using (var tx = uow.BeginTransaction()) {
    // DAL calls
    tx.Commit();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM