Skip to content
plor10 edited this page Nov 15, 2018 · 1 revision

What is a DAO? Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level business services. § 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.

What is DAO? Table: Student, StudentDAO(Interface), StudentDAOImpl(Implements), DAOPatternDemo

Value Object (BEAN) 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 ; } }

Data Access Object Interface import java.util.List ; public interface StudentDao { public List getAllStudents (); public Student getStudent ( int rollNo ); public void updateStudent (Student student); public void deleteStudent (Student student); }

Concrete class implementing Interface import java.util.ArrayList ; import java.util.List ; public class StudentDaoImpl implements StudentDao { //list is working as a database List students; public StudentDaoImpl (){ students = new ArrayList (); Student student1 = new Student("Robert",0); Student student2 = new Student("John",1); students.add (student1); students.add (student2); }

Concrete class implementing Interface – (CONTINUED) @Override public void deleteStudent (Student student) { students.remove ( student.getRollNo ()); System.out.println ("Student: Roll No " + student.getRollNo () + ", deleted from database"); } @Override public List getAllStudents () { 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"); } }

Demonstrate Usage public class DaoPatternDemo { public static void main(String[] args ) { StudentDao studentDao = new StudentDaoImpl (); for (Student student : studentDao.getAllStudents ()) { System.out.println ("Student: " + student.getRollNo () + " " + student.getName () + " ]"); } Student student = studentDao.getAllStudents ().get(0); student.setName ("Michael"); studentDao.updateStudent (student); studentDao.getStudent (0); System.out.println ("Student: " + student.getRollNo () + " " + student.getName () + " ]") } }

Clone this wiki locally