Spring JdbcTemplate的queryForList(String sql , Class elementType)返回非對映實體類的解決方法
一直用ORM,今天用JdbcTemplate再次抑鬱了一次。
首先看下這個方法:
乍一看,我想傳個泛型T(實際程式碼執行中,這個T可以是我自定義的一個Bean),然後就能返回個List<T>,也即泛型的集合(純ORM思想啊!殊不知又挖了個大坑~)
於是乎,出現下面程式碼:
- List<Student> list = jdbcTemplate.queryForList(sql, Student.class);
一執行,發現出異常了:
ERROR [com.ruhuiyun.studentmanager.aop.LogAdvice] - org.springframework.jdbc.IncorrectResultSetColumnCountException: Incorrect column count: expected 1, actual 8:Incorrect column count: expected 1, actual 8
異常很明瞭,需要一個,給人家整成了八個,也就是人家不是存List的。甚為蹊蹺,後一查,發現不是這樣的,又跑偏了~
原來這個T,只支援Integer.class String.class 這種單資料型別的,自己定義的Bean不支援。
解決方法:給你想要返回的(即自己封裝的dto)加上一層對映即可
StringBuffer sbItem=new StringBuffer(); sbItem.append("select * from wsbs_person_pay_item where payid="+ppayDTO.getId()); List<PersonPayItemDTO> ppItemList=jdbctemplate.query(sbItem.toString(),new BeanPropertyRowMapper(PersonPayItemDTO.class));