不正确的结果SetColumnCount异常:列计数不正确:预期 1,实际 38

2022-09-01 21:41:06

我正在使用从数据库中检索Bean。这是我的方法:JdbcTemplate

public List<trackerv3Livedata>  getTrackerData() {
    return List<trackerv3Livedata> live = (List<trackerv3Livedata>) jdbcTemplate.queryForList("select * from mmitrackerv3_livedata where accountid =?",new Object[]{aid}, trackerv3Livedata.class);
}

Trackerv3Livedata豆结构如下:

public class trackerv3Livedata implements Serializable {

    private static final long serialVersionUID = 2409168269491619888L;

    private int deviceid;
    private Long timestamp;
    private Mmitrackerv3Device mmitrackerv3Device;
    private Mmitrackerv3Account mmitrackerv3Account;
    private double latitude;
    private double longitude;
    private Double altitude;
    private Double speedkph;
    private Double heading;
    private Double gpssignal;
    private Integer geozoneid;
    private Double distancekm;
    private Double gsmsignal;
    private Double mainpower;
    private Integer laststatustime;
    private Double internalbattry;
    private Double temperature;
    private Short dinput1;
    private Short dinput2;
    private Short dinput3;
    private Short dinput4;
    private Short dinput5;
    private Short dinput6;
    private Short dinput7;
    private Short dinput8;
    private Short ainput1;
    private Short ainput2;
    private Short ainput3;
    private Short ainput4;
    private Short doutput1;
    private Short doutput2;
    private Short doutput3;
    private Short doutput4;

    /* There are Some Getter And Setter Method With Constructor */
}

在我的场景中,完全有可能不会在我的查询上命中,所以我的问题是我如何绕过以下错误消息。

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

在我看来,我应该只取回一个 null,而不是抛出一个异常。我该如何解决这个问题?提前致谢。


答案 1

JdbcTemplate 方法

queryForList(String sql, Class<T> elementType)

对于单列查询很有用,您只能指定列类型。如果在 ResultSet 中需要多列,则使用起来更准确

query(String sql, RowMapper<T> rowMapper)

作为RowMapper的实现,您可以使用自己的,或者

jdbcTemplate.query(sql, new BeanPropertyRowMapper<T>(clazz));

所以在你的情况下,它可能是:

public List<Trackerv3Livedata> getTrackerData() {
    String sql = "SELECT * FROM mmitrackerv3_livedata mlive " +
                 "JOIN mmitrackerv3_device mdevice ON mlive.accountid = " +
                 "mdevice.accountid WHERE mlive.accountid = " + aid;

    return jdbcTemplate.query(sql,
        new BeanPropertyRowMapper<Trackerv3Livedata>(Trackerv3Livedata.class));
}

答案 2

发生这种情况是因为,您使用的 queryForList 方法将不支持多个列。从 JdbcTemplate 查看 queryForList 的实现

public <T> List<T> More ...queryForList(String sql, Object[] args, Class<T> elementType) throws DataAccessException 
{
    return query(sql, args, getSingleColumnRowMapper(elementType));
}

getsingleColumnRowMapper() 方法创建一个新的 RowMapper,用于从单个列读取结果对象。您可以改用下面给出的方法。

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

推荐