Data Access Object Pattern
## Data Access Object Pattern
The Data Access Object (DAO) pattern is used to separate low-level data access APIs or operations from high-level business services. Here are the participants of the Data Access Object pattern.
* **Data Access Object Interface** - This interface defines the standard operations to be performed on a model object.
* **Data Access Object concrete class** - This class implements the above interface. This class is responsible for getting data from a data source which can be a database, or an XML file, or any other storage mechanism.
* **Model Object/Value Object** - This object is a simple POJO containing get/set methods to store data retrieved using the DAO class.
* * *
## Summary
### Intent
Separate the data access logic from the business logic and encapsulate the data access operations in a dedicated class.
### Problem it Solves
* Solves the problem of tight coupling between business logic and data access logic, improving code maintainability and reusability.
### Use Cases
* When you need to centralize the data access logic of an application to simplify business logic and make data operations easier.
### Implementation
* **Define DAO Interface**: Declare methods for data access operations.
* **Implement DAO Class**: Implement the DAO interface, encapsulating all access logic to the data source (e.g., a database).
* **Data Transfer Object (DTO)**: Optional, used to encapsulate data retrieved from the data source.
### Key Code
* **DAO Interface**: Declares methods for data access and manipulation.
* **DAO Implementation**: Provides the concrete implementation of the DAO interface, containing the code to access the database.
### Application Example
* **User Management Application**: The User DAO class is responsible for interacting with the database, managing CRUD operations for user data.
### Advantages
1. **Separation of Concerns**: Separates data access logic from business logic, reducing system coupling.
2. **Easy to Maintain**: Data access logic is centrally managed, making it easier to maintain and update.
3. **Scalability**: Changing the data source or modifying data access logic does not affect the business logic layer.
### Disadvantages
* **May Increase Complexity**: For simple applications, introducing the DAO pattern might add an extra layer of abstraction.
### Recommendations
* Use the DAO pattern when an application needs to interact with multiple data sources or when the data access logic is complex.
### Considerations
* DAO classes should be as simple as possible, containing only data access logic, not business logic.
### Main Roles Involved
1. **DAO Interface**:
* Declares methods for data access and manipulation.
2. **DAO Implementation**:
* Implements the DAO interface, encapsulating all access logic to the data source.
3. **Data Transfer Object (DTO) (Optional)**:
* Encapsulates data retrieved from the data source, used for data transfer between the business logic layer and the data access layer.
4. **Business Logic Layer**:
* Uses the DAO interface to interact with the data source, without directly depending on the specific implementation of data access.
5. **Data Source**:
* Database or other persistent storage, with which the DAO implementation interacts to store and retrieve data.
The Data Access Object pattern helps keep an application clean and manageable by providing a clear data access layer.
* * *
## Implementation
We will create a _Student_ object as the model object or value object. _StudentDao_ is the data access object interface. _StudentDaoImpl_ is the concrete class implementing the data access object interface. _DaoPatternDemo_, our demo class, uses _StudentDao_ to demonstrate the usage of the Data Access Object pattern.

## Step 1
Create a value object.
## Student.java
public class Student{private String name; private int rollNo; Student(String name, int rollNo){this.name = name; this.rollNo = rollNo; }public String getName(){return name; }public void setName(String name){this.name = name; }public int getRollNo(){return rollNo; }public void setRollNo(int rollNo){this.rollNo = rollNo; }}
## Step 2
Create the data access object interface.
## StudentDao.java
import java.util.List; public interface StudentDao{public ListgetAllStudents(); public Student getStudent(int rollNo); public void updateStudent(Student student); public void deleteStudent(Student student); }
## Step 3
Create a concrete class implementing the above interface.
## StudentDaoImpl.java
import java.util.ArrayList; import java.util.List; public class StudentDaoImpl implements StudentDao{Liststudents; public StudentDaoImpl(){students = new ArrayList(); Student student1 = new Student("Robert",0); Student student2 = new Student("John",1); students.add(student1); students.add(student2); } @Override public void deleteStudent(Student student){students.remove(student.getRollNo()); System.out.println("Student: Roll No " + student.getRollNo() +", deleted from database"); } @Override public ListgetAllStudents(){return students; } @Override public Student getStudent(int rollNo){return students.get(rollNo); } @Override public void updateStudent(Student student){students.get(student.getRollNo()).setName(student.getName()); System.out.println("Student: Roll No " + student.getRollNo() +", updated in the database"); }}
## Step 4
Use _StudentDao_ to demonstrate the usage of the Data Access Object pattern.
## DaoPatternDemo.java
public class DaoPatternDemo{public static void main(String[]args){StudentDao studentDao = new StudentDaoImpl(); for(Student student : studentDao.getAllStudents()){System.out.println("Student: [RollNo : " +student.getRollNo()+", Name : "+student.getName()+" ]"); }Student student =studentDao.getAllStudents().get(0); student.setName("Michael"); studentDao.updateStudent(student); studentDao.getStudent(0); System.out.println("Student: [RollNo : " +student.getRollNo()+", Name : "+student.getName()+" ]"); }}
## Step 5
Execute the program, and you will see the following output:
Student: [RollNo : 0, Name : Robert ]Student: [RollNo : 1, Name : John ]Student: Roll No 0, updated in the database Student: [RollNo : 0, Name : Michael ]
YouTip