1

I'm getting the following issue from Sonar: SampleDao.java null Use try-with-resources or close this "PreparedStatement" in a "finally" clause.

And I'm using Spring JDBC with the following code:

ResponseObject user = jdbcTemplate.query(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(MY_QUERY);
            ps.setLong(1, parameter);
            return ps;
        }
    }, new MyResultSetExtractor());

My question is that I think I don't need to close the connection because I have a connection pool, so what do you think I have to do, just ignore the sonar issue ? or is there anything else I can do?.

Thank you

  • A connection pool usually gives you an implementation that releases the connection back to the pool when closed. Following the Liskov substitution rule, you should not assume your connection's implementation and you should always close it if its contract states so. – Jazzwave06 Jan 30 '18 at 22:35
  • Spring `JdbcTemplate` will ensure that the `PreparedStatement` object is closed as needed, so you need to tell SonarQube not to warn you about this instance. See [Turning Sonar off for certain code](https://stackoverflow.com/q/10971968/5221149). – Andreas Jan 30 '18 at 22:48
  • 1
    @sturcotte06 If your code didn't allocate the connection, then you shouldn't be the one to close it, unless explicitly documented. As here Spring is the one allocating the connection, it is Spring that should close it (unless spring explicitly documents that you need to close the connection). – Mark Rotteveel Jan 31 '18 at 09:44
  • @MarkRotteveel Yeah you're right, I read the question but hadn't checked the code. – Jazzwave06 Jan 31 '18 at 14:16

1 Answers1

-3

This seems to be an issue as you are creating an anonymous inner class and sonar expects the prepare statement created in a regular method to be closed.

If you are using java 8 try replacing anonymous inner class with labmda expression.

ResponseObject user = jdbcTemplate.query(coneection -> {
        PreparedStatement ps = con.prepareStatement(MY_QUERY);
        ps.setLong(1, parameter);
        return ps;
    }
}, new MyResultSetExtractor());
Anil Bachola
  • 289
  • 2
  • 5