Returning Connection using a method is a common practice,
For example in Hikari's HikariConnectionProvider
public Connection getConnection() throws SQLException
{
Connection conn = null;
if (this.hds != null) {
conn = this.hds.getConnection();
}
return conn;
}
But Sonar warns about closing connection
Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwise an exception could keep the call from being made.
I want to return a Connection I can use later, so I can't close it in those methods
How/if can I avoid such warning on main method to return valid connection?
EDIT Added a false positive bug in Sonar community: S2095 report on method return Connection
EDIT 2 Issue isn’t reproducible on latest version
I have faced the similar issue while creating connection with mongodb. So, what I just made connection object Autowired as I was using spring.
In this way the life cycle of connection object was managed by spring and we don't have to close the connection explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With