JdbcTempate处理mysql TINYINT返回Boolean的问题

   当mysql中类型为"TINYINT UNSIGNED"或者"TINYINT "时,用JDBC取出记录时,getObject()得到的是boolean类型,这时必须用getInt()才行。

   spring JdbcTemplate的API 默认是直接调用rs.getObject()处理的,所以需要扩展它的方法,处理过程如下:

1. 使用JdbcTemplate的RowMapper API

public <T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper) throws DataAccessException {
		return query(sql, args, new RowMapperResultSetExtractor<T>(rowMapper));
	}

2. JdbcTemplate的queryForList和queryForMap都是ColumnMapRowMapper,覆盖其mapRow方法,主要就是增加一个类型判断:

  private static class MyColumnMapRowMapper extends ColumnMapRowMapper {

        public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            Map<String, Object> mapOfColValues = createColumnMap(columnCount);
            for (int i = 1; i <= columnCount; i++) {

                String key = getColumnKey(JdbcUtils.lookupColumnName(rsmd, i));
                Object obj = null;
                if (rsmd.getColumnTypeName(i).equals("TINYINT")) {
                    obj = rs.getInt(i);
                } else {
                    obj = getColumnValue(rs, i);
                }
                mapOfColValues.put(key, obj);

            }
            return mapOfColValues;
        }
    }

3. 使用

   protected RowMapper<Map<String, Object>> getColumnMapRowMapper() {
        return new MyColumnMapRowMapper();
    }

   readJdbc.queryForMap(sql, params, getColumnMapRowMapper());

猜你喜欢

转载自san-yun.iteye.com/blog/1842319