我有两节课
class Deptartment{
int deptid,
String deptname;
List<Employee> employees;
}
class Employee{
int empid;
String empname;
int deptid;
}
Table:
Department:
deptid,deptname
Employee
empid,empname,deptid
Query: select * from deptartment d,employee e where d.deptid= e.deptid
现在我如何使用 spring jdbc 模板填充 Department 对象?
为了帮助 Sean Patrick Floyd,这是他使用单个查询的解决方案:
final Map<Integer, Department> departments = new HashMap<Integer, Department>();
this.jdbcTemplate.query(
"select d.deptid, d.deptname, e.empid, e.empname from Department d inner join Employee on e.deptid = e.deptid",
new RowMapper<Employee>() {
public Department mapRow(ResultSet rs, int rowNum) throws SQLException {
Integer deptId = rs.getInt("deptid");
Department d = (Department) departments.get(deptId);
if (d == null) {
String deptName = rs.getString("deptname");
d = new Department();
d.setDeptId(deptId);
d.setDeptName(deptName);
departments.put(deptId, d);
}
Employee employee = new Employee();
employee.setEmpId(rs.getInt("empid"));
employee.setEmpName(rs.getString("empname"));
employee.setDeptId(deptId);
d.getEmployees().add(employee);
return employee;
}
});
List<Department> result = new ArrayList<Department>(departments.values());
它恰好更短且更高效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)