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
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.