5

我有两节课

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 对象?

4

3 回答 3

10

为了帮助肖恩·帕特里克·弗洛伊德,这是他通过单个查询的解决方案:

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());    

它恰好更短,更有效。

于 2011-06-29T14:42:55.897 回答
2

Spring 目前没有直接支持这种场景。但是,您可以使用建议包含在未来版本的 Spring 中的以下MultipleRowMapper类。

于 2011-06-29T14:12:41.537 回答
0

这样的事情会做:

Department department = this.jdbcTemplate.queryForObject(
        "select deptid, deptname from Department where deptid = :deptid",
        new Object[deptid],
        new RowMapper<Department>() {
            public Department mapRow(ResultSet rs, int rowNum) throws SQLException {
                Department department = new Department();
                department.setDeptid(rs.getInt("deptid"));
                department.setDeptname(rs.getString("deptname"));
                return department;
            }
        });
department.setEmployees(this.jdbcTemplate.query(
        "select empid, empname from Employee",
            new RowMapper<Employee>() {
                public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Employee employee = new Employee();
                    employee.setEmpid(rs.getInt("emptid"));
                    employee.setEmpname(rs.getString("empname"));
                    return department;
                }
            });
于 2011-06-29T14:20:29.503 回答