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

References

  1. Spring JdbcTemplate JavaDoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
4 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
4 Comment authors
BalaSurya DeSudhir RavindramohanJames Ortiz Recent comment authors
newest oldest most voted
Bala
Guest
Bala

Thank you It saved my time. int count = getJdbcTemplate().queryForObject(sql, new Object[] { username }, Integer.class); worked for me.

Surya De
Guest
Surya De

Late to the party but shouldn’t we also be handling if the queryForObject returns a null? That’s quite possible.

Sudhir Ravindramohan
Guest
Sudhir Ravindramohan

Thanks, do you have an idea of why are these convenient methods being phased out?

James Ortiz
Guest
James Ortiz

thank you!