Data Access Object Pattern
Data Access Object Pattern
Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or
operations from high level business services. Following are the participants in Data Access Object
Pattern.
Data Access Object Interface - This interface defines the standard operations to be
performed on a model object(s).
Data Access Object concrete class - This class implements above interface. This class is
responsible to get data from a data source which can be database / xml or any other storage
mechanism.
Model Object or Value Object - This object is simple POJO containing get/set methods to
store data retrieved using DAO class.
Implementation
We are going to create a Student object acting as a Model or Value Object.StudentDao is Data Access
Object Interface.StudentDaoImpl is concrete class implementing Data Access Object Interface.
DaoPatternDemo, our demo class, will use StudentDao to demonstrate the use of Data Access Object
pattern.
Step 1
Step 2
import java.util.List;
Step 3
import java.util.ArrayList;
import java.util.List;
public StudentDaoImpl(){
students = new ArrayList<Student>();
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
}
@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 th
}
}
Step 4
Use the StudentDao to demonstrate Data Access Object pattern usage.
DaoPatternDemo.java
//update student
Student student =studentDao.getAllStudents().get(0);
student.setName("Michael");
studentDao.updateStudent(student);
//get the student
studentDao.getStudent(0);
System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " +
}
}
Step 5
Verify the output.