mercredi 22 juillet 2020

Java DAO Pattern - Separate Database Communication Responsibility Without Using Multiple Classes

Hoping to leverage the knowledge of the community to help me answer a question on the DAO pattern in Java Programming.

Searching google for examples of implementing the DAO pattern give results like this:Example DAO Pattern

  public class DaoPatternDemo {
   public static void main(String[] args) {
      StudentDao studentDao = new StudentDaoImpl();

      //print all students
      for (Student student : studentDao.getAllStudents()) {
         System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
      }


      //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 : " + student.getName() + " ]");     
   }
}

My question is this: Is there a clean way to utilize just the Student model/class to communicate with the database on behalf of students rather than implement a "StudentDao" class as well? I would much rather do something like this:

student.setName("Michael");

and have the Student class handle all the database communication to set the name of the student upon calling the setName() method rather than have to do this:

student.setName("Michael");
studentDao.updateStudent(student);

It seems like if you follow the DAO pattern you have to do everything twice: Update the Student Object and the Student Table in the Database. Wouldn't it be easier to just have the methods in the Student Class take care of updating the database as well? What would be the drawbacks of a design like that?

(Example code and image taken from: https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm)

Aucun commentaire:

Enregistrer un commentaire