Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sonar squid:S2095 when method return Connection

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

like image 297
user7294900 Avatar asked Aug 06 '26 06:08

user7294900


1 Answers

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.

like image 52
Ghil Maan Avatar answered Aug 07 '26 19:08

Ghil Maan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!