The DAO Pattern: Examples, Advantages and Disadvantages

Lecture



1. Overview

The Data Access Object (DAO) pattern is a structural pattern that allows us to isolate the application/business layer from the persistence layer (usually a relational database, but it could be any other persistence mechanism) using an abstract API.

The functionality of this API is to hide from the application all the complexities involved in performing CRUD operations in the underlying storage mechanism. This allows both layers to evolve separately without knowing anything about each other.

In this tutorial, we'll dive deep into the implementation of the pattern and learn how to use it to abstract calls to a JPA Entity Manager.

2. A Simple Implementation

To understand how the DAO pattern works, let's create a basic example.

Let's say we want to develop an application that manages users. To keep the application's domain model completely agnostic about the database, we'll create a simple DAO class that will take care of keeping these components neatly decoupled from each other.

2.1. The Domain Class

Since our application will work with users, we need to define just one class to implement its domain model:

 The DAO Pattern: Examples, Advantages and Disadvantages

The User class is just a plain container for user data, so it doesn't implement any other behavior worth stressing.

Of course, the most important design choice we need to make here is how to keep the application that uses this class isolated from any persistence mechanism that could be implemented at some point.

Well, that's exactly the problem that the DAO pattern attempts to address.

2.2. The DAO API

Let's define a basic DAO layer so we can see how it can completely decouple the domain model from the persistence layer.

Here's the DAO API:

 The DAO Pattern: Examples, Advantages and Disadvantages

From a bird's-eye view, it's clear that the Dao interface defines an abstract API that performs CRUD operations on objects of type T .

Thanks to the high level of abstraction that the interface provides, it's easy to create a concrete, fine-grained implementation that works with User objects.

2.3. The UserDao Class

Let's define a user-specific implementation of the Dao interface:

 The DAO Pattern: Examples, Advantages and Disadvantages

The DAO Pattern: Examples, Advantages and Disadvantages

The UserDao class implements all the functionality required to fetch, update and delete User objects.

  • For simplicity's sake, the users List acts like an in-memory database, which is populated with a couple of User objects in the constructor **

Of course, it's easy to refactor the other methods so that they can work, for instance, with a relational database.

While both the User and UserDao classes coexist independently within the same application, we still need to figure out how the latter can be used to keep the persistence layer hidden from the application's logic:

 The DAO Pattern: Examples, Advantages and Disadvantages

The example is contrived, but it shows in a nutshell the motivations behind the DAO pattern. In this case, the main method just uses a UserDao instance to perform CRUD operations on a few User objects.

  • The most relevant aspect of this process is how UserDao hides from the application all the low-level details on how the objects are persisted, updated and deleted **.

3. Using the Pattern With JPA

There's a common tendency among developers to think that the release of JPA reduced the functionality of the DAO pattern to zero, as the pattern becomes just another layer of abstraction and complexity implemented on top of the one provided by the JPA entity manager.

Certainly, in some scenarios this is true. Even so, sometimes we just want to expose to our application only a few domain-specific methods of the entity manager's API. In such cases, the DAO pattern has its place.

3.1. The JpaUserDao Class

With that in mind, let's create a new implementation of the Dao interface so we can see how it can encapsulate the functionality that the JPA entity manager provides out of the box:

 The DAO Pattern: Examples, Advantages and Disadvantages

The DAO Pattern: Examples, Advantages and Disadvantages

  • The JpaUserDao class is able to work with any relational database supported by the JPA implementation. **

Also, if we look at the class closely, we'll realize how the use of https://en.wikipedia.org/wiki/Composition over inheritance[Composition]and Dependency Injection allows us to call only the entity manager methods required by our application.

Simply put, we have a domain-specific API, rather than the entire entity manager's API.

3.2. Refactoring the User Class

In this case, we'll use Hibernate as the default JPA implementation, so we'll refactor the User class accordingly:

 The DAO Pattern: Examples, Advantages and Disadvantages

3.3. Bootstrapping a JPA Entity Manager Programmatically

Assuming that we already have a working MySQL instance running either locally or remotely, and a database table "users" populated with some user records, we need to obtain a JPA entity manager so we can use the JpaUserDao class to perform CRUD operations in the database.

In most cases, we accomplish this via the typical "persistence.xml" file, which is the standard approach

In this case, we'll take an xml-less approach and get the entity manager with plain Java through Hibernate's handy https://docs.jboss.org/hibernate/orm/5.0/javadocs/org/hibernate/ . jpa/boot/internal/EntityManagerFactoryBuilderImpl.html[EntityManagerFactoryBuilderImpl] class.

For a detailed explanation of how to bootstrap a JPA implementation with Java, please follow the link:/java-bootstrap-jpa[this article].

3.4. The UserApplication Class

Finally, let's refactor the initial UserApplication class so that it can work with a JpaUserDao instance and run CRUD operations on User entities:

  The DAO Pattern: Examples, Advantages and Disadvantages

Even though the example is fairly limited, it's still useful for showing how to integrate the DAO pattern's functionality with the one provided by the entity manager.

In most applications, there's a DI framework that is responsible for injecting a JpaUserDao instance into the UserApplication class. For simplicity's sake, we've omitted the details of this process.

The most important point to note here is how the JpaUserDao class helps to keep the UserApplication class completely agnostic about how the persistence layer performs CRUD operations **.

In addition, we could swap MySQL for any other RDBMS (and even for a flat database) in the future, and our application would still work as expected, thanks to the level of abstraction provided by the Dao interface and the entity manager.

Advantages of Using the DAO Design Pattern

The DAO design pattern, or Data Access Object pattern, is a good example of the object-oriented principles of abstraction and encapsulation. It separates the persistence logic into a separate layer called the data access layer, which allows the application to react safely to changes in the persistence mechanism. For example, if you move from a file-based persistence mechanism to a database, your change will be limited to the data access layer and will not affect the service layer or the domain objects. The Data Access Object, or DAO pattern, is pretty much standard in Java applications, whether it is a core Java, web or enterprise application. Below are a few more benefits of using the DAO pattern in a Java application:

The DAO Pattern: Examples, Advantages and Disadvantages

  1. The DAO design pattern also provides loose coupling between different parts of the application. With the DAO design pattern, your presentation layer is completely independent of the DAO layer, and only the service layer depends on it, which is in turn abstracted through the DAO interface.

  2. The DAO design pattern makes JUnit tests run faster, because it allows you to create mocks and avoid connecting to a database to run the tests. This improves testing, because it is easier to write a test with mock objects than an integration test with a database. If any problems occur when running a unit test, you only need to check the code, not the database. It also protects against database connection and environment problems.

  3. Since the DAO pattern is interface-based, it also promotes the object-oriented design principle "program to an interface, not an implementation", which leads to flexible, high-quality code.

  4. The strength of the DAO pattern is that it lets you create a good abstraction layer over the real storage system. It provides a more object-oriented view of the persistence layer and a clear separation between the domain and the code that will actually perform the data access (direct JDBC, persistence frameworks, an ORM, or even JPA).

  5. Common calls for retrieving objects.
  6. Once you have set up the general create/read/update/delete flow, the common layout can be repeated for other DAOs.
  7. It also consolidates where a particular piece of your code can go. It separates business logic from other components of your code.
  8. abstract separation
  9. a single point of definition for the DB table to object attribute mapping
  10. a transparent ability to implement DAOs for other types of storage
  11. develop an interface template that all DAOs follow
  12. developing a more or less standard JUnit test class for DAO results in better test coverage
  13. full control over the specifics
  14. no performance loss due to an overly generic solution
  15. The abstraction over the real database access implementation separates the data access strategy from the user's business logic. This allowed us to choose a short-term implementation strategy (the Spring JDBC template) for the initial phase of the project, with the option of moving to iBATIS or Hibernate later. (A choice we cannot make at present.)
  16. This separation provides significant testability benefits, since the entire data access implementation can be mocked in a unit test. (This is probably the biggest advantage.)
  17. Combining this with Spring allows us to inject any DB implementation into the system of our choice (although this perhaps says more about DI than about the DAO pattern).

Disadvantages of Using the DAO Pattern

  1. it is one more layer that complicates systems ... But I think that is the price to pay for not tying your code to the underlying persistence API.
  2. It is not the most flexible thing.
  3. If you want to lazy-load some child objects, you will either have to mix the DAO with other layers or take precautions when trying to fetch lazy objects.
  4. If you write DAOs by hand, the code can become tedious and repetitive.
  5. a lot of boilerplate code

4. Conclusion

In this article, we took an in-depth look at the key concepts of the DAO pattern, how to implement it in Java, and how to use it on top of a JPA entity manager.

See also

  • Row Data Gateway
  • Active Record
  • Table Data Gateway
  • Data Mapper
  • [[b4701]]
  • [[b7703]]



See also

created: 2020-10-07
updated: 2026-09-29
280



Was this answer useful?
Choose a quick rating so we can improve the next answer for you.
How satisfied are you?


Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Web site or software design"

Terms: Web site or software design