如何使用jdbcTemplate将多行设置为pojo类变量

时间:2015-11-19 09:36:17

标签: java spring jdbctemplate

我是Spring的新手,我正在尝试从表中获取数据并使用spring jdbcTemplate设置为pojo类,如下面的代码,

@RequestMapping(value = "/getdevicedata/{macId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public DeviceAnalyse getDevicedata(@PathVariable String macId, HttpServletResponse response) throws Exception {
        DeviceAnalyse deviceAnalyse = new DeviceAnalyse();
        //List<DeviceAnalyse> deviceAnalyse = new ArrayList<>();
        if (!isValidMacId(macId)) {
            deviceAnalyse.setDId("Invalid device Id");
            return deviceAnalyse;

        }
        DeviceAnalyse temp = new DeviceAnalyse();
        try{
                    temp = new DeviceAnalyse();
                    String sql = "select value,serverTimeStamp,sensorType,percentage from tablename";
                    temp = (DeviceAnalyse)jdbcTemplate.queryForObject(sql, new Object[]{macId}, new BeanPropertyRowMapper(DeviceAnalyse.class));
                    deviceAnalyse.setPercentage(temp.getPercentage());
                    deviceAnalyse.setSensorType(temp.getSensorType());
                    deviceAnalyse.setServerTimeStamp(temp.getServerTimeStamp());
                    deviceAnalyse.setValue(temp.getValue());

        }
        catch(Exception e){
                    System.out.println(e);
                    e.printStackTrace();
                    deviceAnalyse.setPercentage(0L);
                    deviceAnalyse.setSensorType("");
                    deviceAnalyse.setServerTimeStamp(null);
                    deviceAnalyse.setValue(0L);
        }

        return deviceAnalyse;
    }

这里的DeviceAnalyse是我的pojo类,它有所有的getter setter。但我得到不正确的结果大小:预期1,实际4

如何修复此问题并将所有检索值设置为pojo类?像

while(resultset.next())
{
   deviceAnalyse.setPercentage(temp.getPercentage());
   deviceAnalyse.setSensorType(temp.getSensorType());
   deviceAnalyse.setServerTimeStamp(temp.getServerTimeStamp());                                      
   deviceAnalyse.setValue(temp.getValue());
}

1 个答案:

答案 0 :(得分:1)

你在代码中犯了一个简单的错误。您应该致电jdbcTemplate.query而不是jdbcTemplate.queryForObject

jdbcTemplate.queryForObject预计结果中只有一行,因为RowMapperResultSetExtractor会被1初始化。相反,jdbcTemplate.query会返回所有行。

不要忘记将temp变量更改为List<DeviceAnalyse>

调用jdbcTemplate可能如下所示:

List<DeviceAnalyse> temp = jdbcTemplate.query(sql, new Object[]{macId}, new BeanPropertyRowMapper(DeviceAnalyse.class));