使用 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;
    }

}

因此,我們有一個示例,我們將看到如何使用資料訪問物件設計模式。