问题描述
使用JdbcTemplate的queryForList发生如下异常:
代码语言:javascript复制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)
相关代码如下:
代码语言:javascript复制@Override
public List<Order> findAll() {
return jdbcTemplate.queryForList("select * from tb_order", Order.class);
}
错误原因
首先看该方法的对第二个参数的解释:
代码语言:javascript复制/**
* @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。
解决方案
使用如下方法替换:
代码语言:javascript复制jdbcTemplate.query("select * from tb_order", new OrderRowMapper());
OrderRowMapper实现了RowMapper接口的mapRow方法,通过该方法进行相应的字段处理。
代码语言:javascript复制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;
}
}