代码之家  ›  专栏  ›  技术社区  ›  James

DAOS管理事务的设计是否糟糕?

  •  8
  • James  · 技术社区  · 14 年前

    我一直在读太阳蓝图 GenericDAO 实现和gavin King将此应用于Hibernate。他似乎没有提到交易处理:

    public abstract class GenericHibernateDAO<T, ID extends Serializable> {
        protected Session getSession() {
            return HibernateUtil.getSessionFactory().getCurrentSession();
        }
    
        public T makePersistent(T entity) {
            getSession().saveOrUpdate(entity);
            return entity;
        }
    }
    

    我不知道该把交易的开始/结束放在哪里。Currently they are inside the DAOs that extend this GenericHibernateDAO

    public class FooHibernateDAO extends GenericHibernateDAO<Foo, Long> {
        public Foo saveFoo(Foo foo) {
            getSession().beginTransaction();
            makePersistent(foo);
            getSession().getTransaction().commit();
        }
    }
    

    事务处理应该由应用层中DAO的调用方管理吗?

    2 回复  |  直到 14 年前
        1
  •  16
  •   Teja Kantamneni    14 年前

    通常,最佳实践是在服务层而不是DAO层管理事务。每个DAO方法通常处理一个特定的操作,一个服务方法将它们聚合到一个事务中。

        2
  •  3
  •   Eric Petroelje    14 年前

    应在应用层中管理事务。例如,假设您有一个账户DAO:

    public class AccountDAO {
       public void DebitAccount( int accountId, int dollars ) {
    
       }
    
       public void CreditAccount( int accountId, int dollars ) {
       }
    }
    

    如果我想在账户间转账,我会打电话给 DebitAccount 一个原因是 CreditAccount 在另一个方面。I would want these calls to happen in the same transaction. DAO不可能知道这一点,但是应用层会知道。

    如果在DAO层管理事务,则需要创建另一个 TransferMoney 在DAO上的方法在一个事务中执行。这最终会膨胀您的DAO层,对于复杂的操作,引入可能不应该存在的业务逻辑。如果您有一个操作需要在一个事务中涉及多个DAO,那么它会变得更加混乱。