This are the code try with resources block.
try (Connection con = jdbcTemplate.getDataSource().getConnection();
PreparedStatement preparedStatement = con.prepareStatement(sql);
Statement statement = con.createStatement()) {
....
}
You could write it like this:
The thing is that a
DataSource
is notAutoClosable
. 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 wasnull
. An explicitnull
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.