如果有一个复杂对象Teacher,其实有个Student类型的属性
class Teacher {
private String name;
private Student student;
}
class Student {
private string name;
}
使用BeanPropertyRowMapper转换嵌套对象时往往出现如下报错
Caused by: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'xxx' for property 'xxxx': no matching editors or conversion strategy found
此时如果想自定义一个Convertor可能并不方便。
可以考虑自定义一个CustomBeanPropertyRowMapper类,继承BeanPropertyRowMapper,然后重写BeanPropertyRowMapper中的 protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd)方法。在此方法中对特殊类型的属性进行自定义转换。完整代表如下:
public class CustomBeanPropertyRowMapper<T> extends BeanPropertyRowMapper<T> {
public CustomBeanPropertyRowMapper(Class<T> type) {
super(type);
}
protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd) throws SQLException {
Class<?> propertyType = pd.getPropertyType();
String name = pd.getName();
if (name.equals("student")) {
return JSON.parseObject(rs.getString(index), propertyType);
}
return JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
}
}
在使用JDBCTemplate查询时,就可以如下使用:
public <T> T get(String tablename, Long id, Class<T> entityClass) {
StringBuilder sql = new StringBuilder();
String tableNameRel = convertTableName(tablename);
sql.append("SELECT * FROM ").append(tableNameRel)
.append(" WHERE ").append("id").append("=?");
return jdbcTemplate.queryForObject(sql.toString(), new CustomBeanPropertyRowMapper<>(entityClass), id);
}
以此记录,仅供参考。