Sonar "Close Connection" warning workaround.
When you use Spring and Ibatis and SQLTemplates, you could have code in your project which looks somewhat like this:
Connection connection = DataSourceUtils.getConnection(getDataSource());
...<do connection stuff here>...
DataSourceUtils.releaseConnection(connection, getDataSource());
Sonar will report that you did not close the connection, while in fact, Spring did that for you. You can not just add a "connection.close()" to the code because the whole point of calling "releaseConnection()" is to have Spring handle all the smart stuff on committing, closing, and returning the connection to the pool if needed.
In our company, not closing the connection is a major blocking violation (and it should be). But in this case, there is no way to make the Jedi wave to Sonar, telling it that "this code will do just fine". So I added the following trick, albeit a bit dirty:if (connection.isClosed()){
// This code is only here to keep Sonar from
// warning us that the connection is not
// closed. Please note: Do not just close an
// unclosed connection, Spring should handle
// connection closing and returning to the pool.
connection.close();
}
Use it to your advantage, but use this responsibly. If you see any problems in my solution, or if there is a better way to do this I'd be happy to hear about it.
Edit (2009-12-01):
There is a much better way to do this if you have Spring/Ibatis integration. In stead of DataSourceUtils.getConnection() you can create a new ConnectionCallback object, like so:
JdbcTemplate template = new JdbcTemplate(getDataSource());
Object resultObject = template.execute(new ConnectionCallback() {
public Object doInConnection(Connection conn)
throws SQLException, DataAccessException {
// Do connection stuff here (can return object);
return null;
});
Please note that this code does NOT contain any Connection.close() references. The connection is passed to you, you can use it, and after your method completes, the framework will do whatever is needed to clean everything up. Sonar will not complain because the whole open/close handeling is done outside your method.