Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using spring jdbc template for populating results

I have two classes

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

Now how can i populate Department object using spring jdbc template?

like image 224
akshay Avatar asked Jun 29 '11 14:06

akshay


2 Answers

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.

like image 102
JB Nizet Avatar answered Oct 15 '22 19:10

JB Nizet


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.

like image 41
axtavt Avatar answered Oct 15 '22 20:10

axtavt