using spring jdbc template for populating results

∥☆過路亽.° 提交于 2019-12-04 08:18:58

To help Sean Patrick Floyd, here's his solution with a single query :

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

It happens to be shorter and more efficient.

There is no direct support of this scenario in Spring currently. However, you can use the following MultipleRowMapper class proposed for inclusion into future versions of Spring.

Something like this will do:

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;
                }
            });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!