Keyholder.getKey() can return null - Spring Boot Jdbctemplate

Asked

Viewed 130 times

0

The thing is, I’m a beginner in Spring and I’m doing a method that will insert a new row into a database table and this method will return the Id new that was generated by the Bank, I am doing this way:

public Profissional insert(Profissional profissional) {

    PreparedStatementCreator psc = connection -> {
        PreparedStatement ps = connection.prepareStatement("insert into profissional(texto) values(?)",
                new String[] { "id" });

        ps.setString(1, profissional.getDsNomeProfissional());

        return ps;
    };

    KeyHolder keyHolder = new GeneratedKeyHolder();

    this.jdbc.update(psc, keyHolder);

    profissional.setIdProfissional(keyHolder.getKey().longValue());

    return profissional;
}

and is working and returning the id generated by the bank, but on this line profissional.setIdProfissional(keyHolder.getKey().longValue()); to IDE you’re warning me that keyHolder.getKey().longValue() can return null, and I am worried about it but also with doubt Docs of the Spring You’re saying this is the right way, is it even possible? If yes, can someone explain to me if there is any other way to make this code without danger of returning one Id null?

(Note: this is a more informative question in case someone else has this same doubt that I.)

1 answer

1


The question is old, but as I’ve been through this problem recently, there goes:

What happens is that a Number variable (or any other wrapper Integer, Long, Double, etc...) can receive a null value, so in a hypothetical case where the Keyholder has a null value, the conversion will pop an Npe, so our compiler friend displays this warning.

To solve this case, in particular, it is enough:

if (keyHolder.getKey() != null) {
    profissional.setIdProfissional(keyHolder.getKey().longValue());
}

This code can generate other problems, eg: should not be inserted a value with idProfissional = null... But ai is another case.

  • 1

    Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.