gpt4 book ai didi

java - Spring jdbcTemplate数据访问和java算法

转载 作者:行者123 更新时间:2023-12-01 09:32:03 24 4
gpt4 key购买 nike

我有一种方法必须在 DAO 中返回数据。

部门型号:

public class Department implements Serializable {
private Long id;
private String departmentName;
private List<Employees> employeesInThisDepartment;
// getters and setters...
}

员工模型:

public class Employees implements Serializable {

private Long id;
private String department;
private String fullName;
private Date birthday;
private int salary;
// getters and setters...
}

DAO 中的方法:

@Override
public Department findByDepartmentNameWithEmployees(String departmentName) {
String sql = "select d.id, d.departmentName, e.id, e.fullName, e.department, e.birthday" +
", e.salary from department as d left join employees as e on d.departmentName = e.department " +
"where lower(d.departmentName) = lower(:departmentName)";
Map<String, Object> map = new HashMap<>();
map.put("departmentName", departmentName);
return jdbcTemplate.queryForObject(sql, map, (rs, rowNum) -> {
Department department = new Department();
department.setId(rs.getLong("department.id"));
department.setDepartmentName(rs.getString("department.departmentName"));
department.setEmployeesInThisDepartment(new ArrayList<>());

while (rs.next()){
Employees employees = new Employees();
employees.setId(rs.getLong("employees.id"));
employees.setFullName(rs.getString("employees.fullName"));
employees.setDepartment(rs.getString("employees.department"));
employees.setBirthday(rs.getDate("employees.birthday"));
employees.setSalary(rs.getInt("employees.salary"));
department.getEmployeesInThisDepartment().add(employees);
}
return department;
});
}

此方法必须返回一个部门,其中包含在该部门工作的所有员工的列表,但它错过了列表中的第一个员工。为什么会发生这种情况? (SQL部分工作正常,我认为问题出在循环上?)

最佳答案

对,循环中的问题。根据docs :

Implementations must implement this method to map each row of data in the ResultSet.

因此您不需要调用rs.next(),只需删除此循环包装器并移动 block

    Department department = new Department();

department.setEmployeesInThisDepartment(new ArrayList<>());

外部返回jdbcTemplate.queryForObject(sql, map, (rs, rowNum) -> { ... }。即:

Department department = new Department();
department.setEmployeesInThisDepartment(new ArrayList<>());

jdbcTemplate.queryForObject(sql, map, (rs, rowNum) -> {
department.setId(rs.getLong("department.id"));
department.setDepartmentName(rs.getString("department.departmentName"));

Employees employees = new Employees();
employees.setId(rs.getLong("employees.id"));
employees.setFullName(rs.getString("employees.fullName"));
employees.setDepartment(rs.getString("employees.department"));
employees.setBirthday(rs.getDate("employees.birthday"));
employees.setSalary(rs.getInt("employees.salary"));
department.getEmployeesInThisDepartment().add(employees);
});
return department;

关于java - Spring jdbcTemplate数据访问和java算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39325526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com