Dan*_*ean 101 java spring jdbc jdbctemplate
JdbcTemplate中的queryforInt/queryforLong方法在Spring 3.2中已弃用.我无法找出使用这些方法替换现有代码的最佳做法的原因或内容.
一种典型的方法:
int rowCount = jscoreJdbcTemplate.queryForInt(
"SELECT count(*) FROM _player WHERE nameKey = ? AND teamClub = ?",
playerNameKey.toUpperCase(),
teamNameKey.toUpperCase()
);
Run Code Online (Sandbox Code Playgroud)
好的,上面的方法需要重写如下:
Object[] params = new Object[] {
playerNameKey.toUpperCase(),
teamNameKey.toUpperCase()
};
int rowCount = jscoreJdbcTemplate.queryForObject(
"SELECT count(*) FROM _player WHERE nameKey = ? AND teamClub = ?",
params, Integer.class);
Run Code Online (Sandbox Code Playgroud)
显然,这种弃用使JdbcTemplate类更简单(或者它?).QueryForInt总是一种方便的方法(我猜)并且已经存在了很长时间.为什么删除它.结果代码变得更加复杂.
Gab*_*res 107
我认为有人意识到queryForInt/Long方法具有令人困惑的语义,也就是说,从JdbcTemplate源代码中可以看到它的当前实现:
@Deprecated
public int queryForInt(String sql, Object... args) throws DataAccessException {
Number number = queryForObject(sql, args, Integer.class);
return (number != null ? number.intValue() : 0);
}
Run Code Online (Sandbox Code Playgroud)
这可能会导致您认为如果结果集为空它将返回0,但它会抛出异常:
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
所以以下实现基本上等同于当前的实现:
@Deprecated
public int queryForInt(String sql, Object... args) throws DataAccessException {
return queryForObject(sql, args, Integer.class);
}
Run Code Online (Sandbox Code Playgroud)
然后,现在必须用丑陋的代码替换未弃用的代码:
queryForObject(sql, new Object { arg1, arg2, ...}, Integer.class);
Run Code Online (Sandbox Code Playgroud)
或者这个(更好):
queryForObject(sql, Integer.class, arg1, arg2, ...);
Run Code Online (Sandbox Code Playgroud)
SGB*_*SGB 34
我同意原来的海报,即弃用方便方法queryForLong(sql)是不方便的.
我使用Spring 3.1开发了一个应用程序,并且刚刚更新到最新的Spring版本(3.2.3),并注意到它已被弃用.
幸运的是,对我来说这是一个改变:
return jdbcTemplate.queryForLong(sql); // deprecated in Spring 3.2.x
Run Code Online (Sandbox Code Playgroud)
被改为
return jdbcTemplate.queryForObject(sql, Long.class);
Run Code Online (Sandbox Code Playgroud)
并且几个单元测试似乎表明,上述变化有效.
Mar*_*sta 13
替换此类代码:
long num = jdbcTemplate.queryForLong(sql);
Run Code Online (Sandbox Code Playgroud)
使用此代码:
long num = jdbcTemplate.queryForObject(sql, Long.class);
Run Code Online (Sandbox Code Playgroud)
是非常危险的,因为如果列具有空值,则queryForObject返回null并且我们知道原始类型不能为null并且您将具有NullPointerException.编译器没有警告你这件事.您将在运行时了解此错误.如果您有返回基本类型的方法,则会出现相同的错误:
public long getValue(String sql) {
return = jdbcTemplate.queryForObject(sql, Long.class);
}
Run Code Online (Sandbox Code Playgroud)
Spring 3.2.2中JdbcTemplate中不推荐使用的方法queryForLong具有以下主体:
@Deprecated
public long queryForLong(String sql) throws DataAccessException {
Number number = queryForObject(sql, Long.class);
return (number != null ? number.longValue() : 0);
}
Run Code Online (Sandbox Code Playgroud)
你看,在它们返回原始值之前,检查它是否为null,如果为null则返回0.顺便说一下 - 应该是0L.
归档时间: |
|
查看次数: |
82646 次 |
最近记录: |