JdbcTemplate queryForInt / Long在Spring 3.2.2中已弃用。应该用什么代替? [英] JdbcTemplate queryForInt/Long is deprecated in Spring 3.2.2. What should it be replaced by?

查看:250
本文介绍了JdbcTemplate queryForInt / Long在Spring 3.2.2中已弃用。应该用什么代替?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JdbcTemplate中的queryforInt / queryforLong方法在Spring 3.2中已弃用。我无法找出使用这些方法替换现有代码的最佳做法的原因或原因。

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 these methods.

一种典型的方法:

int rowCount = jscoreJdbcTemplate.queryForInt(
    "SELECT count(*) FROM _player WHERE nameKey = ? AND teamClub = ?",
    playerNameKey.toUpperCase(),
    teamNameKey.toUpperCase()
);

确定上述方法需要重写如下:

OK the above method needs to be re-written as follows:

Object[] params = new Object[] { 
   playerNameKey.toUpperCase(), 
   teamNameKey.toUpperCase()
};
int rowCount = jscoreJdbcTemplate.queryForObject(
    "SELECT count(*) FROM _player WHERE nameKey = ? AND teamClub = ?",
    params, Integer.class);

显然这种弃用使得JdbcTemplate类更简单(或者是吗?)。 QueryForInt总是一种方便的方法(我猜)并且已经存在了很长时间。为什么删除它。结果代码变得更加复杂。

Obviously this deprecation makes the JdbcTemplate class simpler (or does it?). QueryForInt was always a convenience method (I guess) and has been around a long time. Why has it been removed. The code becomes more complicated as a result.

推荐答案

我认为有人意识到queryForInt / Long方法具有令人困惑的语义,也就是说,从JdbcTemplate源代码中可以看到它的当前实现:

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);
}

这可能会让您认为如果结果集为空它将返回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:结果大小不正确:预期为1,实际为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);

或者这个(更好):

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

这篇关于JdbcTemplate queryForInt / Long在Spring 3.2.2中已弃用。应该用什么代替?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆