Java 使用JdbcTemplate 中的queryForList發(fā)生錯誤解決辦法
在開發(fā)項目中遇到JdbcTemplate 中的queryForList發(fā)生錯誤,很是頭疼,在網(wǎng)上找了相關(guān)資料,可以幫忙解決,這里記錄下,
一、問題描述:
查詢時使用JdbcTemplate 中的queryForList發(fā)生錯誤,如下:
查詢方法如下:
1
|
jdbcTemplate.queryForList(selectSql.toString(), entityClass) |
查詢sql如下:
1
|
select * from test where 1 = 1 order by create_time desc limit 0 , 10 |
錯誤如下:
1
|
Incorrect column count: expected 1 , actual 5 |
二、解決方案:
1、上面錯誤的原因是,查詢返回的結(jié)果列期望為1,但實際返回的是5列,因為test表中有5個字段,故返回5列。而這個方法參數(shù)的解釋是這樣的:
1
2
3
|
Parameters: sql SQL query to execute elementType the required type of element in the result list ( for example, Integer. class ) |
就是第2個參數(shù)在網(wǎng)上說只能是簡單類型String或Integer。
2、使用query查詢
1
|
jdbcTemplate.query(selectSql.toString(), rowMapper) |
但多了一個參數(shù)rowMapper,這個參數(shù)需要定義為:
1
2
3
4
5
6
7
|
@SuppressWarnings ( "unused" ) private BeanPropertyRowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(entityClass){ @Override protected void initBeanWrapper(BeanWrapper bw) { super .initBeanWrapper(bw); } }; |
具體的作用就是進(jìn)入查詢結(jié)果轉(zhuǎn)換成實體。
到這步也就解決問題了。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://fanshuyao.iteye.com/blog/2383851