JdbcTemplate queryForInt() is Deprecated
Upgrading Spring version and noticed that queryForInt()
is deprecated, what should be replaced by?
private boolean isUserExists(String username) {
String sql = "SELECT count(*) FROM USERS WHERE username = ?";
boolean result = false;
//The method queryForInt(String, Object...) from the type JdbcTemplate is deprecated
int count = getJdbcTemplate().queryForInt(sql, new Object[] { username });
if (count > 0) {
result = true;
}
return result;
}
Solution
Both queryForInt()
and queryForLong()
are deprecated since version 3.2.2 (correct me if mistake). To fix it, replace the code with queryForObject(String, Class)
.
private boolean isUserExists(String username) {
String sql = "SELECT count(*) FROM USERS WHERE username = ?";
boolean result = false;
int count = getJdbcTemplate().queryForObject(
sql, new Object[] { username }, Integer.class);
if (count > 0) {
result = true;
}
return result;
}
Review the Spring source code.
JdbcTemplate.java
package org.springframework.jdbc.core;
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
//...
@Deprecated
public long queryForLong(String sql, Object... args) throws DataAccessException {
Number number = queryForObject(sql, args, Long.class);
return (number != null ? number.longValue() : 0);
}
@Deprecated
public int queryForInt(String sql, Object... args) throws DataAccessException {
Number number = queryForObject(sql, args, Integer.class);
return (number != null ? number.intValue() : 0);
}
even I replaces queryForInt with queryForObject getting as it is deprecated
Thank you It saved my time. int count = getJdbcTemplate().queryForObject(sql, new Object[] { username }, Integer.class); worked for me.
Late to the party but shouldn’t we also be handling if the queryForObject returns a null? That’s quite possible.
Thanks, do you have an idea of why are these convenient methods being phased out?
thank you!