使用 Java 的数据访问对象 J2EE 设计模式
数据访问对象(DAO) 设计模式是标准的 J2EE 设计模式。
在此设计模式中,数据通过包含从数据库或其他源(称为数据访问对象) 访问数据的方法的类进行访问。标准做法假设有 POJO 类。DAO 可以与其他设计模式混合以访问数据,例如使用 MVC(模型视图控制器),命令模式等。
以下是 DAO 设计模式的示例。它有一个 Employee 类,一个名为 EmployeeDAO 的 Employee DAO 和一个用于演示示例的 ApplicationView 类。
Employee.java
public class Employee {
private Integer employeeId;
private String firstName;
private String lastName;
private Integer salary;
public Employee(){
}
public Employee(Integer employeeId, String firstName, String lastName, Integer salary) {
super();
this.employeeId = employeeId;
this.firstName = firstName;
this.lastName = lastName;
this.setSalary(salary);
}
//standard setters and getters
}
EmployeeDAO
public class EmployeeDAO {
private List<Employee> employeeList;
public EmployeeDAO(List<Employee> employeeList){
this.employeeList = employeeList;
}
public List<Employee> getAllEmployees(){
return employeeList;
}
//add other retrieval methods as you wish
public Employee getEmployeeWithMaxSalary(){
Employee employee = employeeList.get(0);
for (int i = 0; i < employeeList.size(); i++){
Employee e = employeeList.get(i);
if (e.getSalary() > employee.getSalary()){
employee = e;
}
}
return employee;
}
}
ApplicationView.java
public class ApplicationView {
public static void main(String[] args) {
// See all the employees with data access object
List<Employee> employeeList = setEmployeeList();
EmployeeDAO eDAO = new EmployeeDAO(employeeList);
List<Employee> allEmployees = eDAO.getAllEmployees();
for (int i = 0; i < allEmployees.size(); i++) {
Employee e = employeeList.get(i);
System.out.println("UserId: " + e.getEmployeeId());
}
Employee employeeWithMaxSalary = eDAO.getEmployeeWithMaxSalary();
System.out.println("Maximum Salaried Employee" + " FirstName:" + employeeWithMaxSalary.getFirstName()
+ " LastName:" + employeeWithMaxSalary.getLastName() + " Salary: " + employeeWithMaxSalary.getSalary());
}
public static List<Employee> setEmployeeList() {
Employee employee1 = new Employee(1, "Pete", "Samprus", 3000);
Employee employee2 = new Employee(2, "Peter", "Russell", 4000);
Employee employee3 = new Employee(3, "Shane", "Watson", 2000);
List<Employee> employeeList = new ArrayList<>();
employeeList.add(employee1);
employeeList.add(employee2);
employeeList.add(employee3);
return employeeList;
}
}
因此,我们有一个示例,我们将看到如何使用数据访问对象设计模式。