1.实体类
2.BeanPropertyRowMapper和EntityRowMapper(全文重点)
在使用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,其他情况,可以自定义的类来取值。
3.示例
3.1 BeanPropertyRowMapper
RowMapper<RcSysEnterpriseMaintenanceEntity> rowMapper=new BeanPropertyRowMapper<RcSysEnterpriseMaintenanceEntity>(RcSysEnterpriseMaintenanceEntity.class);
//读取多个对象
List<RcSysEnterpriseMaintenanceEntity> query = jdbcTemplate.query(" select enterprise_name enterpriseName,label_id labelId from t_rc_enterprise_maintenance ", rowMapper);
for (RcSysEnterpriseMaintenanceEntity e : query) {
System.out.println(e.getEnterpriseName()+"------------");
}
//读取单个对象 (一个? 对应一个参数值)
RcSysEnterpriseMaintenanceEntity queryForObject = jdbcTemplate.queryForObject(" select enterprise_name enterpriseName,label_id labelId from t_rc_enterprise_maintenance where id=? ", rowMapper,"8072350128245829632");
System.out.println(queryForObject.getEnterpriseName()+"++++++++++++");
// 【注意】:1、使用BeanProperytRowMapper要求sql数据查询出来的列和实体属性需要一一对应。如果数据中列明和属性名不一致,在sql语句中需要重新取一个别名
// 2、使用JdbcTemplate对象不能获取关联对象
3.2 EntityRowMapper
/////
4.统计函数,平均函数,求和函数
String sql="select count(*) from t_rc_enterprise_maintenance";
int count= jdbcTemplate.queryForObject(sql, Integer.class);
System.out.println(count);