Why put a DAO layer over a persistence layer (like JDO or Hibernate)

前端 未结 10 802
梦谈多话
梦谈多话 2021-01-31 09:13

Data Access Objects (DAOs) are a common design pattern, and recommended by Sun. But the earliest examples of Java DAOs interacted directly with relational databases -- they were

10条回答
  •  生来不讨喜
    2021-01-31 09:16

    One word: transactions

    Take the situation where I have to perform two data update operations in a single transaction. These operations together form a logical unit of work. My business logic wants to express itself in terms of that unit of work, and it doesn't want to bother itself with transaction boundaries.

    So I write a DAO. Take this pseudo code using Spring transactions and hibernate:

    edited to remove HQL that was offending @Roger so much but which wasn't relevant to the point

    @Transactional
    public void doUnitOfWork() {
      // some persistence operation here
      // some other persistence operation here
    }
    

    My business logic calls doUnitOfWork(), which begins a transaction, performs both persistence operations, and then commits. It neither knows nor cares about the transaction, or what operations are performed.

    Furthermore, if the DAO implements an interface with the doUnitOfWork() method, then the business logic can code to the interface, making it easier to unit test.

    Generally, I always wrap my data access operations in a DAO, and whack an interface around it.

提交回复
热议问题