Java Reference
In-Depth Information
data source by providing an interface via which the various layers can communicate with the
data source.
This chapter discusses the original problem that the DAO solved and its relevance in modern Java
EE applications. Also examined are the role of the related data transfer object (DTO) and how it
and the factory pattern i t together with the DAO. In addition, this chapter covers the use of the JPA
and ORM in the context of the DAO. You'll see an implementation of the DAO and how to improve
it by using generics. Finally, you will read about the changed role of the pattern and why it is still a
valid design pattern.
WHAT IS A DATA ACCESS PATTERN?
The original solution that the DAO pattern proposed was dei ned in the topic Core J2EE Patterns:
Best Practices and Design Strategies 1 as follows:
Use a data access object (DAO) to abstract and encapsulate all access to the data
source. The DAO manages the connection with the data source to obtain and store
data.
The problem that was solved with the abstraction and encapsulation of the data source was to guard
against the application being dependent on the data source implementation. This decoupled the
business layer from the data source. It was thought that if the data source changed, the decoupling
would reduce or negate any impact. However, in reality, the data source rarely changed—not even
between vendors of the same source type such as between Postgre and MS SQL. It is hard to imag-
ine that a decision would be made to migrate an SQL data source to an XML l at i le system, LDAP
repository, or web service. This simply didn't happen. So what value does the DAO pattern have in
modern Java EE? Do you really need this pattern?
The DAO pattern is still a valuable pattern, and its original solution is still valid, although the
motivation for its implementation has changed in its emphasis. Rather than guarding against
the impact of an unlikely change in the data source type, the value is in its mockability and
testability and its use in structuring the code and keeping it clean of data access code. There is
still value in using it as a way to encapsulate legacy data storage systems and to simplify access
to complex implementations of data sources. However, these are more likely to be corner and
exceptional cases.
The DAO pattern encapsulates CRUD operations in an interface that is implemented by a con-
crete class. This interface can be mocked and therefore easily tested, avoiding a connection to the
database. Testing is improved because writing tests using mocks is easier than integrating tests with
a live database. The DAO's concrete implement uses low‐level APIs such as JPA and Hibernate to
perform the CRUD operations.
Data Access Class Diagram
Figure 12-1 shows the class diagram of the DAO, demonstrating the interaction between the
client and the DAO and the DTO. Not shown is the optional factory that produces the DAO
instance.
 
Search WWH ::




Custom Search