Spring JdbcTemplate的queryForList(String sql , Class<T> elementType)返回非映射实体类的解决方法

 一直用ORM,今天用JdbcTemplate再次抑郁了一次。

           首先看下这个方法:

          乍一看,我想传个泛型T(实际代码执行中,这个T可以是我自定义的一个Bean),然后就能返回个List<T>,也即泛型的集合(纯ORM思想啊!殊不知又挖了个大坑~)

          于是乎,出现下面代码:

  1. 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));

原文地址:https://www.cnblogs.com/weiyi1314/p/7240922.html