总是看到什么什么dao的,但是Dao到底是什么?Dao是一种设计模式,全称Data Access Object Patter。下面翻译一篇小文章,以作解释。
Data Access Object Pattern 或者DAO 模式被用来分离低层次数据访问和高级业务逻辑操作。下面是一些DAO模式中包含的元素。
· Data Access Object Inte易做图ce - 定义了一个model类上标准的操作方法的接口。
· Data Access Object concrete class - 实现了上面接口的类。这个类负责从数据存储区(数据库、xml)中取得数据。
· Model Object or Value Object - 这是一个简单地POJO(plain Old Java Object)包含了getter和setter方法。由DAO类进行存取。
实现
创建一个Student类代表了Model或Value对象。StudentDao是一个Dao接口。StudentDaoImpl是一个实现StudentDao的类。见下图:
STEP 1.
创建model类,Student
[java]
package com.wly.dp.dao;
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.
创建一个Dao接口,StudentDao
[java]
package com.wly.dp.dao;
import java.util.List;
public inte易做图ce StudentDao {
public List<Student> getAllStudents();
public Student getStudent(int rollNo);
public void updateStudent(Student student);
public void deleteStudent(Student student);
}
STEP 3.
创建一个实现Dao接口的类,StudentDaoImpl
[java]
package com.wly.dp.dao;
import java.util.ArrayList;
import java.util.List;
public class StudentDaoImpl implements StudentDao{
List<Student> students; //模拟数据库
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 List<Student> 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");
}
@Override
public void deleteStudent(Student student) {
students.remove(student.getRollNo());
System.out.println("Student: Roll No " + student.getRollNo()
+", deleted from database");
}
}
STEP 4.
测试类,Test
[java]
package com.wly.dp.dao;
public class Test {
public static void main(String[] args) {
StudentDao studentDao = new StudentDaoImpl();
// 输出所有student
for (Student student : studentDao.getAllStudents()) {
System.out.println("Student: [RollNo : " + student.getRollNo()
+ ", Name : " + student.getName() + " ]");
}
// 更新一个student
Student student = studentDao.getAllStudents().get(0);
student.setName("Michael");
studentDao.updateStudent(student);
// 得到更新后的student
studentDao.getStudent(0);
System.out.println("Student: [RollNo : " + student.getRollNo()
+ ", Name : " + student.getName() + " ]");
}
}
STEP 5.
验证输出
[java]
Student: [RollNo : 0, Name : Robert ]
Student: [RollNo : 1, Name : John ]
Student: Roll No 0, updated in the database
Student: [RollNo : 0, Name : Michael ]