JdbcTemplate queryForInt/Long is deprecated in Spring 3.2.2. What should it be replaced by?

后端 未结 6 1466
慢半拍i
慢半拍i 2021-01-30 19:36

The queryforInt/queryforLong methods in JdbcTemplate are deprecated in Spring 3.2. I can\'t find out why or what is considered the best practice to replace existing code using t

6条回答
  •  猫巷女王i
    2021-01-30 19:42

    Replacing such code:

    long num = jdbcTemplate.queryForLong(sql);
    

    With this code:

    long num = jdbcTemplate.queryForObject(sql, Long.class);
    

    is very dangerous because if column have null value queryForObject return null and as we know primitive types can't be null and You will have NullPointerException. The compiler didn't warn You about this. You will know about this error at runtime. The same error You will have if You have method that return primitive type:

    public long getValue(String sql) {
        return = jdbcTemplate.queryForObject(sql, Long.class);
    }
    

    The deprecated method queryForLong in JdbcTemplate in Spring 3.2.2 have the following body:

    @Deprecated
    public long queryForLong(String sql) throws DataAccessException {
        Number number = queryForObject(sql, Long.class);
        return (number != null ? number.longValue() : 0);
    }
    

    You see before they return primitive value there is check that this is not null and if it is null they return 0. By the way - Should be 0L.

提交回复
热议问题