J2EE patterns: DAO and data-source isolation
The DAO pattern (Data Access Object) is one of the basic J2EE patterns. It is worth
understanding if you want to build flexible applications, including web applications. If
the words J2EE pattern make you nervous, rest easy. J2EE is simply
the category DAO was put in. This article
follows on loosely from A quick tour of ORM.
Purpose
It puts an interface between a data source and its consumers and isolates
the logic for retrieving data in a single layer.
Motivation
Applications vary, and so do the data sources
they use. Traditional examples include relational databases,
object databases and the like. Applications often use other,
more specific sources such as web services.
These sources and others have their own ways to retrieve data.
Relational databases use SQL and their object-relational counterparts use something
similar. The sources can change between deployments. An application may have to work
with both MySQL and Oracle, and web services may be
replaced by XML files.
In practice, the worst case with this variety of data sources is
application logic full of branches like “if the database is Oracle, then…”
At best we have a persistence layer shielding us, but what happens if
we need to change it for performance reasons, for instance? Another problem is scattering
the data retrieval logic all over the place, with the problems that entails.
DAOs (Data Access Objects) solve this by providing an interface for
working with the data and implementing the necessary logic. The application layer uses
the DAO layer, which shields it from the data sources and puts
all the retrieval logic in one place.

The class diagram shows the IDao interface used by the application logic,
which is shielded from the concrete DAO implementation that encapsulates the individual data sources.
Data can pass between the DAO and the application logic in
POJOs, for example. Selecting
a concrete DAO for a particular environment can be handled by an IoC framework
(see Dagblog, May 17, 2004, J2EE patterns: Inversion of Control and Dependency Injection) or
by implementing the Factory pattern.
For more on DAO:
- Core J2EE Pattern Catalog, Core J2EE Patterns — Data Access Object
- Design Patterns — Data Access Object
- Sean C. Sullivan, Advanced DAO programming
Related articles
Related CZ Podcast episodes
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio
- #1 · Vývojová prostředí v Javě
The first CZ Podcast episode looks at Java development environments. · Czech audio