1

I'm trying to query for a set and return it as a hash map object with Spring JdbcTemplate. But some reasons I'm getting empty result set from server. It is possible that I have a problem in the overall configuration but the rest of the queries are working without problems.

This is how I query

public Map<Integer, String> getCompanyDataservers() {
    return getTemplate().queryForObject("select id, dataserver from company", new RowMapper<Map<Integer,String>>() {
        @Override
        public Map<Integer, String> mapRow(ResultSet rs, int rowNum)
                throws SQLException {
            HashMap<Integer, String> toReturn = new HashMap<Integer, String>();
            while(rs.next()) {
                int id = rs.getInt("id");
                toReturn.put(id, dataserver);
            }
            return toReturn;
        }});
}

After some debugging and logging statements I concluded that my resultset seems to be empty of any rows. When I query the same ("select id, dataserver from company") manually directly from DB I get the desired result. Yet this way I get a resultset with 0 rows.

One of my theories is that can't get get this kind of set when querying for a object this way. But isn't there a possibility to be free at you queries and construct a more elaborate object as a query result, or I have to create a purpose built class to be used by "queryForList" to get the desired data and convert it afterwards?

Or am I just missing something?

4

1 回答 1

4

You are not supposed to invoke rs.next() inside mapRow. JdbcTemplate will invoke mapRow for you for every row in the resultset

All you need to do on mapRow is just return a HashMap which represent one single database row, spring will do the resultset iteration for you

于 2013-07-18T23:11:46.117 回答