Main Tutorials

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 Author

author image
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

Subscribe
Notify of
5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Alekhya
1 year ago

even I replaces queryForInt with queryForObject getting as it is deprecated

Bala
8 years ago

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

Surya De
8 years ago

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

Sudhir Ravindramohan
8 years ago

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

James Ortiz
9 years ago

thank you!