Home > Net >  Sonar issue: A "NullPointerException" could be thrown; "getDataSource()" can ret
Sonar issue: A "NullPointerException" could be thrown; "getDataSource()" can ret

Time:08-03

This are the code try with resources block.

try (Connection con = jdbcTemplate.getDataSource().getConnection();
                PreparedStatement preparedStatement = con.prepareStatement(sql);
                Statement statement = con.createStatement()) {
    
         ....
}

CodePudding user response:

That code is wrong on more then one level. You have a JdbcTemplate and just use it as a carrier for the DataSource instead of using it properly.

Depending on what you want to do you should use one of the query or execute methods on the JdbcTemplate instead of obtaining the DataSource and getting the Connection.

If you really want the Connection use a ConnectionCallback with an execute method instead.

jdbcTemplate.execute( (Connection con) -> {
  PreparedStatement preparedStatement = con.prepareStatement(sql);
  Statement statement = con.createStatement();
})

But as mentioned you probably should be using one of the query methods instead of doing what youa re doing now!.

CodePudding user response:

You could write it like this:

   DataSource ds = jdbcTemplate.getDataSource();
   if (ds != null) {
       try (Connection con = ds.getConnection();
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            Statement statement = con.createStatement()) {

            ....
       }
   }

The thing is that a DataSource is not AutoClosable. Therefore there is no need to manage it with the try with resources.

Furthermore, if the DataSource >is< null, you won't be able to get a connection or a statement, and there is probably nothing that you could sensibly in the try body if the statement was null. An explicit null test will avoid all of that.

But if we take into account the way that JdbcTemplate is designed to be used, I think that @M.Deinum's answer gives better ways to solve this.

  • Related