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

后端 未结 6 1444
慢半拍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条回答
  •  走了就别回头了
    2021-01-30 20:02

    What I think is that somebody realized that the queryForInt/Long methods has confusing semantics, that is, from JdbcTemplate source code you can see its current implementation:

    @Deprecated
    public int queryForInt(String sql, Object... args) throws DataAccessException {
        Number number = queryForObject(sql, args, Integer.class);
        return (number != null ? number.intValue() : 0);
    }
    

    which may lead you to think that if the result set is empty it will return 0, however it throws an exception:

    org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

    so the the following implementation is essentially equivalent to the current one:

    @Deprecated
    public int queryForInt(String sql, Object... args) throws DataAccessException {
        return queryForObject(sql, args, Integer.class);
    }
    

    And then the non deprecated code now must be replaced with the ugly:

        queryForObject(sql, new Object { arg1, arg2, ...}, Integer.class);
    

    or this (nicer):

        queryForObject(sql, Integer.class, arg1, arg2, ...);
    

提交回复
热议问题