Sonarlint wrong NullPointerException warning (S2259) when reusing HibernateTemplate

  • Operating system: MacOS
  • Programming language you’re coding in: Java
  • Connected to SonarCloud or SonarQube (and which version): 8.9.6

And a thorough description of the problem / question:

Nullable annotated function causes a false positive error.
I call getHibernateTemplate function from package org.springframework.orm.hibernate5.support package. Even though there is a null check it shows a blocker error.

            if (getHibernateTemplate() != null) {
                getHibernateTemplate().delete(persistentInstance);
                LOG.debug("delete successful");
            }

Hi @ugur_tas,

SonarLint cannot be sure if the value returned by getHibernateTemplate() is always the same or changes between calls (could be changed by another thread, for example). That’s why the issue is raised.

The easy workaround is to store the value in a local variable:

var hibernateTemplate = getHibernateTemplate();
if (hibernateTemplate != null) {
    hibernateTemplate.delete(persistentInstance);
    LOG.debug("delete successful");
}