BeanPropertyRowMapper
将数据库查询结果转换为Java类对象。 常应用于使用Spring的JdbcTemplate查询数据库,获取List结果列表,数据库表字段和实体类自动对应。
示例:
@Overridepublic List findAll() {
String sql = "SELECT * FROM user";
/**
* BeanPropertyRowMapper将查询结果转换为类对象
*/
return jdbcTemplate.query(sql, new BeanPropertyRowMapper(Demo.class));}
@Overridepublic List selectUser(int uid) {
String sql = "SELECT * FROM user WHERE id = ?";
/**
* 带条件查询
*/
return jdbcTemplate.query(sql, new Object[]{uid}, new BeanPropertyRowMapper(Demo.class));}
也可以自定义bean属性和db字段的映射
db对应的字段为 create_time,如果直接执行:
{
"current_value":913582,
"id":1,
"key_name":"point_deposit_trade_no",
"step":50,
"update_time":"2019-09-09 18:10:13"
}
没有create_time字段了,如何正确映射呢?
自定义注解,
@Target({ ElementType.TYPE,ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldMapping {
/**
* 匹配规则,格式为key=value,key为属性名,value为列名
* @return
*/
String[] value() default {};
}
在测试用例中使用:
@SqlSetting(query = "select * from pk_config where step=:step")
@FieldMapping({"createtime=create_time"})
List getConfig(@Para(value = "aa") int step);
重写BeanPropertyRowMapper的initialize 方法.
jdbcTemplate.query(String sql, SqlParameterSource paramSource, RowMapperrowMapper) 传入自定义的rowMapper
执行测试用例:
{
"createtime":"2018-01-29 11:49:40",
"current_value":913582,
"id":1,
"key_name":"point_deposit_trade_no",
"step":50,
"update_time":"2019-09-09 18:10:13"
},