DAO pattern - where do transactions fit in?

前端 未结 5 1498
独厮守ぢ
独厮守ぢ 2021-02-05 04:54

So I\'ve got this generic DAO thing going on and at face value it appears to be ok. It\'s basically modeled after the CaveatEmptor sample application from the Hibernate guys.

5条回答
  •  粉色の甜心
    2021-02-05 05:52

    I remember that Martin Fowler advices to keep the control of the transaction in the business layer because transaction is a business problem. (If you design a BankAccount class, a transaction is part of the domain language).

    You can try to implement a TransactionScope as in .NET it works something like that

    using (TransactionScope ts = new TransactionScope())
    {
      ...
    }
    

    It's the same thing as (not exactly but if you are a Java guy, it's more explicit to you)

    TransactionScope scope = new TransactionScope();
    try
    {
     ...
     scope.Commit();
    }
    catch(Exception ex)
    {
      scope.Rollback();
      throw;
    }
    

    To decouple your business layer from any DAO technologies you can add a TransactionFactory in your domain language, which return a ITransactionScope (an interface) that you have defined with a Commit and Rollback methods. This way your domain layer is not bound to your DAO layer, only a concrete implementation of TransactionFactory is.

    ITransactionScope scope = transactionFactory.CreateTransaction();
    try
    {
     ...
     scope.Commit();
    }
    catch(Exception ex)
    {
      scope.Rollback();
      throw;
    }
    

提交回复
热议问题