错误类型提示,如下:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Long
at demo.spring.jdbc.dao.JDBCTemplatePersonDaoImpl.findById(JDBCTemplatePersonDaoImpl.java:26)
at demo.spring.test.TestDataSourceInjection.main(TestDataSourceInjection.java:18)
根据提示找到了对应的内容,如下:
public class JDBCTemplatePersonDaoImpl implements PersonDao {
private JdbcTemplate jdbcTemplate;
//通过IOC注入数据源后,初始化jdbcTemplate对象
public void setDataSource(DataSource dataSource){
jdbcTemplate=new JdbcTemplate(dataSource);
}
@Override
public Person findById(Long id) {
//通过queryForList执行sql语句,返回结果集,结果集类型为Map
List person=jdbcTemplate.queryForList("select * from person where id="+id.longValue());
for(Iterator it=person.iterator();it.hasNext();){
Map personMap=(Map) it.next();
Long p_id=(Long)personMap.get("ID");
String p_name=(String)personMap.get("NAME");
Integer p_age=(Integer)personMap.get("AGE");
Person p=new Person();
p.setId(p_id);
p.setName(p_name);
p.setAge(p_age);
return p;
}
return null;
}
}
解决办法:修改其中两条语句,如下:
Long p_id=((BigDecimal) personMap.get("ID")).longValue();
Integer p_age=((BigDecimal)personMap.get("AGE")).intValue();
记住:不要忘记import java.math.BigDecimal;