Spring Boot使用JdbcTemplate的queryForList异常:Incorrect column count: expected 1, actual 3

问题描述

使用JdbcTemplate的queryForList发生如下异常:

org.springframework.jdbc.IncorrectResultSetColumnCountException: Incorrect column count: expected 1, actual 3

    at org.springframework.jdbc.core.SingleColumnRowMapper.mapRow(SingleColumnRowMapper.java:110)
    at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:94)
    at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:61)
    at org.springframework.jdbc.core.JdbcTemplate$1QueryStatementCallback.doInStatement(JdbcTemplate.java:440)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:376)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:452)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:462)
    at org.springframework.jdbc.core.JdbcTemplate.queryForList(JdbcTemplate.java:485)
    at com.secbro.service.impl.OrderServiceImpl.findAll(OrderServiceImpl.java:50)
    at com.secbro.service.OrderServiceTest.findAll(OrderServiceTest.java:54)

相关代码如下:

@Override
    public List<Order> findAll() {
        return jdbcTemplate.queryForList("select * from tb_order", Order.class);
    }

错误原因

首先看该方法的对第二个参数的解释:

/**
 * @param elementType the required type of element in the result list
 * (for example, {@code Integer.class})
 */
<T> List<T> queryForList(String sql, Class<T> elementType) throws DataAccessException;

实际上该参数只支持简单类型String或Integer。


解决方案

使用如下方法替换:


jdbcTemplate.query("select * from tb_order", new OrderRowMapper());

1

OrderRowMapper实现了RowMapper接口的mapRow方法,通过该方法进行相应的字段处理。


class OrderRowMapper implements RowMapper<Order> {

    @Override
    public Order mapRow(ResultSet rs, int rowNum) throws SQLException {
        // 对数据的返回处理
        Order order = new Order();
        order.setId(rs.getInt("id"));
        order.setOrderNo(rs.getString("orderNo"));
        order.setAmount(rs.getInt("amount"));
        return order;
    }
}
上一篇:halcon学习笔记——(14)算子_开发


下一篇:想要愉快地规划旅游行程?旅游网站Expedia用人脸识别提升用户体验