我有两个类
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());
它恰巧更短,更有效。
关于java - 使用spring jdbc模板填充结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6521937/