如何从 ResultSet 创建对象?

问题描述 投票:0回答:1

我正在尝试编写一个方法来接收 id 并从数据库返回一个对象,但它一直返回 null。

public Seller findById(int id) throws SQLException {

        Seller seller = null;
        String query = "SELECT seller.*, department.name as DepName FROM seller INNER JOIN department ON seller.department_id = department.departmentID WHERE seller.id = ?"; 
        Connection connection = DataBaseConnection.connect();
        pstmt = connection.prepareStatement(query);

        pstmt.setInt(1, id);
        result = pstmt.executeQuery();

        if(result.next()) {
            Department dep = createDepartment(result);
            seller = createSeller(result, dep);
        }

        DataBaseConnection.closeStatement(pstmt);
        DataBaseConnection.closeResultSet(result);

        return seller;
}

private Seller createSeller(ResultSet result, Department dep) throws SQLException {
    int idSeller = result.getInt("id");
    String name = result.getString("name");
    String email = result.getString("email");
    Date birthDate = result.getDate("birthDate");
    double salary = result.getDouble("salary");
    return new Seller(idSeller, name, email, birthDate, salary, dep);
}

private Department createDepartment(ResultSet rs) throws SQLException {
    int depId = rs.getInt("departmentId");
    String depName = rs.getString("name");
    return new Department(depId, depName);
}

createDepartment(result) 和 createSeller(result, dep) 方法应通过将从数据库检索到的数据传递给 Seller 和 Department 类的构造函数来实例化对象。我被困在这个问题上几个小时了,有人可以帮忙吗?

java object constructor crud resultset
1个回答
0
投票

我认为你可以在MySQL命令行上执行语句

© www.soinside.com 2019 - 2024. All rights reserved.