spring JdbcTemplate queryForList 出錯
Incorrect column count: expected 1, actual 5
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
©Copyright 蕃薯耀 2017年7月10日
http://www.cnblogs.com/fanshuyao/
一、問題描述:
查詢時使用JdbcTemplate 中的queryForList發生錯誤,如下:
查詢方法如下:
Java代碼

- jdbcTemplate.queryForList(selectSql.toString(), entityClass)
查詢sql如下:
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);
- }
- };
具體的作用就是進入查詢結果轉換成實體。
到這步也就解決問題了。
今天越懶,明天要做的事越多。