BeanPropertyRowMapper
将数据库查询结果转换为Java类对象。 常应用于使用Spring的JdbcTemplate查询数据库,获取List结果列表,数据库表字段和实体类自动对应。
示例:
@Data
class Student {
private Integer id;
private String name;
private Integer age;
}
@Repository("studentDao")
class StudentDaoImpl implements StudentDao {
@Autowired
@Qualifier("namedParameterJdbcTemplate")
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
private static String SELECT_SQL = " select id,name,age from student ";
@Override
public List<Student> getListByCondition(List<Integer> ids) {
if (CollectionUtils.isNotEmpty(ids)) {
Map<String, Object> params = new HashMap<>();
params.put("ids", ids);
StringBuilder sb = new StringBuilder(SELECT_SQL);
sb.append(" where a.app_id in (:appIds) ");
return namedParameterJdbcTemplate.query(sb.toString(), params,
new BeanPropertyRowMapper<>(Student.class));
}
return Lists.newArrayList();
}
}
注:
- 字段名对应可以有驼峰形式。例如:表中字段为stu_name,实体类中的属性名可以对应stuName。
BeanPropertyRowMapper是Spring框架中用于将数据库查询结果映射到Java类对象的工具,常在JdbcTemplate中使用。当查询数据库并获取List结果时,它能自动匹配表字段和实体类属性。示例展示了如何在StudentDaoImpl中使用BeanPropertyRowMapper从列表条件中获取Student对象列表,即使字段名存在驼峰命名规则也能正确映射。


被折叠的 条评论
为什么被折叠?



