环境:Spring 3.0.
如有entity bean Employee.java和Department.java:
[code="java"]public Class Employee{
private Integer id;
private String name;
private Department department;
....
}
public Class Department{
private Integer id;
private String name;
....
}[/code]
使用关联查询,无法给department赋值:
[code="java"]String sql = "select t1.id,t1.name,t2.id as 't1.department.id',t2.name as 't1.department.name' from Employee t1 inner join Department department on t1.departmentId=department.id where t1.id=?";
return this.jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(Employee.class),1);[/code]
是BeanPropertyRowMapper不支持内嵌对象属性的赋值吗,有什么好的解决方案,谢谢。
sql还有有点让人混淆,因为t2只是department表的别名,而你的domain对象里并没有t2.这样的属性,所以我帮你修改一下sql:
[code="java"]
String sql = "select t1.id,t1.name,t2.id as 'department.id',t2.name as 'department.name' from Employee t1 inner join Department t2 on t1.departmentId=t2.id where t1.id=?";
[/code]
有两种方法解决你的问题
1. List empList = jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(Employee.class),2);
BeanPropertyRowMapper是RowMapper的子类,它的转换方法是在mapRow()方法里实现的,所以可以重构这个方法
[code="java"]
List empList = jdbcTemplate.query(sql, new RowMapper(){
public Employee mapRow(ResultSet rs, int rowNum) {
Employee emp = new Employee();
try {
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
emp.setDepartment(new Department());
emp.getDepartment().setId(rs.getInt("department.id"));
emp.getDepartment().setName(rs.getString("department.name"));
} catch (SQLException e) {
emp = null;
}
return emp;
}
},2);
[/code]
第二个方法,是在你的Employee和Department这两个对象上建立一个EmployeeVO的对象,这个对象的属性是包括两个对象的,如:
[code="java"]
public class EmployeeVO {
private int id;
private String name;
private int departmentId;
private String departmentName;
....
}
[/code]
这样的话,你的sql也要进行修改如下:
[code="java"]
String sql = "select t1.id,t1.name,t2.id as 'departmentId',t2.name as 'departmentName' from Employee t1 inner join Department t2 on t1.departmentId=t2.id where t1.id=?";
[/code]
你这sql语句写错了吧,t2指代的什么
看下官方文档:
[code="java"]Mapping is provided for fields in the target class for many common types, e.g.: String, boolean, Boolean, byte, Byte, short, Short, int, Integer, long, Long, float, Float, double, Double, BigDecimal, java.util.Date, etc. [/code]
没有提到object,应该不支持。
方案1:
使用mybatis,它支持的嵌套对象。
方案2:
自己在代码中封装一下也可以达到目的:
[code="java"]
public Class Employee{
private Integer id;
private String name;
private Department department;
public Department getDepartment() {
if (department == null) {
department = new Department();
}
department.setId(id);
department.setName(name);
}
}
[/code]