jdbcTemplate nullable warning on not null field

668 views Asked by At

When calling select query on not null column so we can expect not null (int) value, Code:

public int getNum() {
    int num = 0;
    try {
        num = jdbcTemplate.queryForObject("select num from mytable", Integer.class);
    } catch (EmptyResultDataAccessException ignored) {
        // ignored not found
    }
    return num;
}

Intellij warns:

Unboxing of 'jdbcTemplate.queryForObject(SQL, Integer.class)' may produce 'NullPointerException'

How can remove Intellij warning by marking value as not null?

I can't mark jdbcTemplate method as @NotNullabe or use @SuppressWarnings

the value returns from SQL is always an int value that can't be null, I just want to indicate the IDE that value can't be null by its DB definition

1

There are 1 answers

5
Christoph Dahlen On

Statement jdbcTemplate.queryForObject("select num from mytable", Integer.class); returns instance of Integer.class, which may be null. Since your variable num is of primitive type int, a NullPointerException will occur during auto-boxing.

Solution:

public int getNum() {
  int num = 0;
  try {
    Integer i = jdbcTemplate.queryForObject("select num from mytable", Integer.class);
    if(i != null) {
      num = i;
    }
  } catch (EmptyResultDataAccessException ignored) {
      // log or rethrow exception
  }
  return num;
}