欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-11 07:59:45
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);  
    }  
  };  

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

到这步也就解决问题了。

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