在使用JdbcTemplate的时候,可以使用query方法来查询指定的sql语句,来返回我们需要的结果。query提供了RowMapper接口,可以方便的将查询结果转换为对象。
RowMapper常见的有2个实现类BeanPropertyRowMapper和EntityRowMapper。在使用上,位置是等价的。
//BeanPropertyRowMapper
List<T> list = jdbcTemplate.query(sql, new Object[] {param1,param2...}, new BeanPropertyRowMapper<>(T.class))
//EntityRowMapper
List<T> list = jdbcTemplate.query(sql, new Object[] {param1,param2...}, new EntityRowMapper<>(T.class));
BeanPropertyRowMapper可以是我们自定义的一个普通类,但是属性需要和返回的列名是一致。
EntityRowMapper则需要是由Entity注解的实体类。属性定义的Column的Name和返回的列名一致。
如果是查询select *,那么可以直接使用实体类的EntityRowMapper,其他情况,可以自定义的类来取值。