Lecture
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.
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 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:
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 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 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 **.
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 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:
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:
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.
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 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.
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.
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.
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).
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.
Comments