Java 使用JdbcTemplate 中的queryForList发生错误解决办法

Java 使用JdbcTemplate 中的queryForList发生错误解决办法

         在开发项目中遇到JdbcTemplate 中的queryForList发生错误,很是头疼,在网上找了相关资料,可以帮忙解决,这里记录下,

一、问题描述: 

查询时使用JdbcTemplate 中的queryForList发生错误,如下: 

查询方法如下:

jdbcTemplate.queryForList(selectSql.toString(), entityClass) 

查询sql如下:

select * from test where 1=1 order by create_time desc limit 0,10 

错误如下:

Incorrect column count: expected 1, actual 5 

二、解决方案:

1、上面错误的原因是,查询返回的结果列期望为1,但实际返回的是5列,因为test表中有5个字段,故返回5列。而这个方法参数的解释是这样的:

Parameters: 
sql SQL query to execute 
elementType the required type of element in the result list (for example, Integer.class) 

 就是第2个参数在网上说只能是简单类型String或Integer。 

2、使用query查询

jdbcTemplate.query(selectSql.toString(), rowMapper) 

 但多了一个参数rowMapper,这个参数需要定义为:

@SuppressWarnings("unused") 
  private BeanPropertyRowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(entityClass){  
    @Override  
    protected void initBeanWrapper(BeanWrapper bw) {  
      super.initBeanWrapper(bw);  
    }  
  };  

具体的作用就是进入查询结果转换成实体。 

到这步也就解决问题了。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!