如何插入和 return 一个 Employee 实例(DAO 模式)

How to insert and return an instance of Employee (DAO pattern)

在方法 save() 中,我收到一个 Employee 实例作为输入,我想将它添加到 table employee 和 return 这个添加的实例中。我读到了这个问题,但没有找到问题的答案。

public Employee save(Employee employee) throws SQLException {
        Connection connection = ConnectionSource.instance().createConnection();
        String sql = "insert into employee VALUES(" +employee.getId() + ", " + "'employee.getFullName().getFirstName()'" + ", " +"'employee.getFullName().getLastName()'"+ ", " +"'employee.getFullName().getMiddleName()'"+ ", " +  "'employee.getPosition()'" + ", " +"'employee.getHired()'"+ ", " + employee.getSalary()+ ", " +employee.getManagerId()+ ", " +employee.getDepartmentId() + ")";
        connection.prepareStatement(sql);

        PreparedStatement ps2 = connection.prepareStatement("select * from employee");

        ResultSet resultSet = ps2.executeQuery();
        resultSet.next();
            Employee emp = new Employee(... );

        return emp;
    }

首先,最好不要使用这样的方法:

String sql = "insert into employee VALUES(" +employee.getId() + ", " + "'employee.getFullName().getFirstName()'" + ", " +"'employee.getFullName().getLastName()'"+ ", " +"'employee.getFullName().getMiddleName()'"+ ", " +  "'employee.getPosition()'" + ", " +"'employee.getHired()'"+ ", " + employee.getSalary()+ ", " +employee.getManagerId()+ ", " +employee.getDepartmentId() + ")";

在那种情况下你可以有一个 sql injection

改为使用

String sql = "insert into employee values (?, ?, ...)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, employee.getId());
statement.setString(2, employee.getFullName().getFirstName());
...

对于你的问题,你可以尝试这样的事情:

public Employee save(Employee employee) throws SQLException {
    try (Connection connection = ConnectionSource.instance().createConnection();;
        PreparedStatement statement = connection.prepareStatement(SQL_INSERT,Statement.RETURN_GENERATED_KEYS);) {
        
        statement.setInt(1, employee.getId());
        statement.setString(2, employee.getFullName().getFirstName());
        // ...

        int affectedRows = statement.executeUpdate();

        if (affectedRows == 0) {
            throw new SQLException("Creating employee failed, no rows affected.");
        }

        try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
            if (generatedKeys.next()) {
                employe.setId(generatedKeys.getLong(1));
            }
            else {
                throw new SQLException("Creating employe failed, no ID obtained.");
            }
        }
        return employee;
    }
}