Uploaded image for project: 'Spring Framework'
  1. Spring Framework
  2. SPR-13220

JdbcTemplate.queryForObject(sql, <primitive>.class) produces TypeMismatchDataAccessException

    XMLWordPrintable

    Details

      Description

      The following code

      int i = jdbcTemplate.queryForObject(sql,int.class);
      

      produces

      org.springframework.dao.TypeMismatchDataAccessException: Type mismatch affecting row number 0 and column type 'null': Value [22] is of type [java.lang.Integer] and cannot be converted to required type [int]
      	at org.springframework.jdbc.core.SingleColumnRowMapper.mapRow(SingleColumnRowMapper.java:101)
      	at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:93)
      	at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60)
      	at org.springframework.jdbc.core.JdbcTemplate$1QueryStatementCallback.doInStatement(JdbcTemplate.java:459)
      	at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:404)
      	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:470)
      	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:480)
      	at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:490)
      	at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:496)
      

      Instead, Spring should convert the Integer to an int.

      Migrating from Spring 4.1 to 4.2

      This bug is much more apparent now that Spring 4.2 removed methods like int queryForInt(String sql). It seems that many users may update the following Spring pre 4.2 code:

      int i = jdbcTemplate.queryForInt(sql);
      

      to be

      int i = jdbcTemplate.queryForObject(sql, int.class);
      

      which would produce the above TypeMismatchDataAccessException. Obviously one could easily do:

      int i = jdbcTemplate.queryForObject(sql, Integer.class);
      

      to workaround the issue.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              juergen.hoeller Juergen Hoeller
              Reporter:
              rwinch Rob Winch
              Last updater:
              Spring Issues Spring Issues
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved:
                Days since last comment:
                3 years, 19 weeks, 5 days ago