本次任务是完成DAO接口实现类开发，并进行单元测试。

## 准备工作

### 安装Git工具

[下载](https://static.seahi.me/2024/12/Git-2.47.1-64-bit.exe)

### 同步项目代码

在桌面上右键，选择 Open Git Bash here

执行命令：

```bash
git clone https://git.seahi.me/用户名/stu学号.git
```


## 任务一：完成DAO接口的实现类

Day 3 任务中已经完成了`StudentdAOImpl`类的实现，接下来继续完成 `TeacherDaoImpl`和`LeaveRequestDAOImpl`类，这两个类分别实现`TeacherDAO`接口和`LeaveRequestDAO`接口。

#### StudentDAOImpl

[StudentDAOImpl.java](https://static.seahi.me/2024/12/StudentDAOImpl.java)

### TeacherDAOImpl

```java
package dao.impl;

import dao.TeacherDAO;
import model.Teacher;
import util.DatabaseUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * TeacherDAO接口的实现类，提供教师数据的数据库访问操作
 * 实现了TeacherDAO接口定义的所有方法，包括基础的CRUD操作和特定的查询方法
 * 使用JDBC与数据库进行交互，所有数据库操作都包含适当的异常处理
 */
public class TeacherDAOImpl implements TeacherDAO {

    /**
     * 插入一条教师记录
     * 将Teacher对象的信息保存到数据库中，并获取生成的主键ID
     * 
     * @param teacher 要插入的教师对象，包含教师的详细信息
     * @return 影响的行数，插入成功返回1，失败返回0
     */
    @Override
    public int insert(Teacher teacher) {
        String sql = "INSERT INTO teachers (teacher_id, name, department, contact, password) VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            
            // 设置预处理语句的参数
            stmt.setString(1, teacher.getTeacherId());
            stmt.setString(2, teacher.getName());
            stmt.setString(3, teacher.getDepartment());
            stmt.setString(4, teacher.getContact());
            stmt.setString(5, teacher.getPassword());
            
            int affectedRows = stmt.executeUpdate();
            if (affectedRows == 0) {
                return 0;
            }

            // 获取自动生成的主键
            try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    teacher.setId(generatedKeys.getInt(1));
                }
            }
            return affectedRows;
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 根据ID删除教师记录
     * 
     * @param id 要删除的教师记录的ID
     * @return 影响的行数，删除成功返回1，失败返回0
     */
    @Override
    public int deleteById(int id) {
        String sql = "DELETE FROM teachers WHERE id = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setInt(1, id);
            return stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    /**
     * 根据ID查询教师信息
     * 
     * @param id 要查询的教师ID
     * @return 如果找到则返回教师对象，否则返回null
     */
    @Override
    public Teacher findById(int id) {
        String sql = "SELECT * FROM teachers WHERE id = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setInt(1, id);
            ResultSet rs = stmt.executeQuery();
            
            if (rs.next()) {
                return mapResultSetToTeacher(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询所有教师记录
     * 
     * @return 包含所有教师对象的列表，如果没有记录则返回空列表
     */
    @Override
    public List<Teacher> findAll() {
        List<Teacher> teachers = new ArrayList<>();
        String sql = "SELECT * FROM teachers";
        try (Connection conn = DatabaseUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            
            while (rs.next()) {
                teachers.add(mapResultSetToTeacher(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return teachers;
    }

    /**
     * 根据工号查询教师信息
     * 
     * @param teacherId 要查询的教师工号
     * @return 如果找到则返回教师对象，否则返回null
     */
    @Override
    public Teacher findByTeacherId(String teacherId) {
        String sql = "SELECT * FROM teachers WHERE teacher_id = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setString(1, teacherId);
            ResultSet rs = stmt.executeQuery();
            
            if (rs.next()) {
                return mapResultSetToTeacher(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将ResultSet映射为Teacher对象
     * 从结果集中提取数据并创建Teacher实例
     * 
     * @param rs 包含教师数据的ResultSet对象
     * @return 映射后的Teacher对象
     * @throws SQLException 如果访问ResultSet时发生错误
     */
    private Teacher mapResultSetToTeacher(ResultSet rs) throws SQLException {
        // TODO 补全代码（参考Day3 任务二.4）
    }
}

```

### LeaveRequestDAOImpl

源文件：[LeaveRequestDAOImpl.java](https://static.seahi.me/2024/12/LeaveRequestDAOImpl.java)

下载后放置到合适的位置


## 任务二：DAO实现类的单元测试

将下列文件放置在 `src/test/dao/impl` 目录中，检查测试是否通过

[TeacherDAOImplTest.java](https://static.seahi.me/2024/12/TeacherDAOImplTest.java)

[LeaveRequestDAOImplTest.java](https://static.seahi.me/2024/12/LeaveRequestDAOImplTest.java)

## 提交代码

在项目目录中，打开 Git Bash，执行：

```bash
git config --global user.email "换成你的邮箱"
git config --global user.name "换成你的用户名"

git add .
git commit -m "完成Day4任务"
git push
```