adam bien's blog

JPA/EJB3 killed the DAO 📎

Regarding to the abstract of the DAO-Pattern: "Access to data varies depending on the source of the data. Access to persistent storage, such as to a database, varies greatly depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation." the DAO tries to decouple the business logic from the proprietary resource. The solution to the problem is the following: "...The DataAccessObject is the primary object of this pattern. The DataAccessObject abstracts the underlying data access implementation for the BusinessObject to enable transparent access to the data source. The BusinessObject also delegates data load and store operations to the DataAccessObject..." [Core J2EE Patterns].

In the practise the DAO-Pattern was often realized by the following items:
  • DAO-Interface (provided a datasource-neutral interface)
  • DAO-Implementation (=access to the datasource implementation)
  • DAO-Factory (the creation of the implementation)
  • Optional: ServiceLocator (location of resources in JNDI)
The main problem in J2EE was the insufficient power of CMP 2.0. The limited query capabilities, no access to native SQL and lack of dynamic queries forced the developers to access the database using plain-JDBC. It was a very good idea to encapsulate the database access behind a replaceable and mockable implementation.
In EJB 3/Java EE 5 environment there is no need to use the low level JDBC to access the database any more. Actually you can use generic, but powerful Query Lanaguae, as well as Native SQL to fetch not only the persistent objects, but also data transfer objects and even primitive data types as well. It is even possible to execute update and delete statements. The JPA comes already with the EntityManager which provides already generic data access functionality. The usage cannot be simpler. The EntityManager will be just injected to the bean-class:

@Stateless
public class CustomerMgrBean implements CustomerMgr{

    @PersistenceContext
    private EntityManager em;

It's just one liner. The DAO pattern is actually no more interesting for general data access, but is still needed to access data from stored procedures, flat files etc. However the bean above can be considered as a "DAO", but very streamlined one...

Readers questions are also discussed in the "Data Access Object--Reader's Questions" post.

[See also an in-depth discussion in the "Real World Java EE Patterns--Rethinking Best Practices" book (Second Iteration, "Green Book"), page 259 in, chapter "Data Access Object"]

See you at Java EE Workshops at MUC Airport!