JdbcTemplate的queryForMap方法報錯
阿新 • • 發佈:2018-11-07
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
JdbcTemplate的queryForMap方法報錯queryForMap方法使用不當,就會出錯,使用方式如下:
The queryForMap method in JdbcTemplate only expects a single row to be returned, The return value for this method will be a map of column names to column values for the single result row.
queryForMap方法返回的結果集大小必須是1,並且返回的map中,以列的名字作為key,獲取的值作為value
1 |
public void test(){ |
2 |
String SQL_GET_ATTRIBUTE= "select * from test where rownum<1" ; |
3 |
Map<Object,Object> map=getJdbcTemplate().queryForMap(SQL_GET_ATTRIBUTE); |
4 |
Set<Entry<Object, Object>> entrySet=map.entrySet(); |
5 |
for (Entry<Object, Object> entry : entrySet) { |
6 |
System.out.println( "key is " + entry.getKey()); |
7 |
System.out.println( "value is " + entry.getValue()); |
8 |
} |
9 |
} |
輸出會列出test所有欄位為key,查詢出來的值為vlaue的字串,這裡使用oracle資料庫,強制使用“where rownum<1”來限制只返回一行。
利用spring 的getJdbcTemplate().queryForMap如果返回空集,就會報
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0 的異常,解決辦法就是捕捉這個異常然後返回null即可。
Java程式碼
- try{
- return getJdbcTemplate().queryForMap("select s.fb,s.pb,s.tu,s.qt,s.fbc,s.pbc,s.tt,s.ft,s.lt from gbc$view_user s where s.ud = ? and ad= ?", new Object[]{ud,ad});
- }catch (EmptyResultDataAccessException e) {
- return null;
- }
解決方案 在queryForMap的地方 try catch 一下 即可。