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.