1

Suppose I want to run two sql queries in a transaction I have code like the below:

jdbi.useHandle(handle -> handle.useTransaction(h -> {
                    var id = handle.createUpdate("some query")
                            .executeAndReturnGeneratedKeys()
                            .mapTo(Long.class).findOne().orElseThrow(() -> new IllegalStateException("No id"));

                    handle.createUpdate("INSERT INTO SOMETABLE (id) " +
                                    "VALUES (:id , xxx);")
                            .bind("id")
                            .execute();
            
                }
        ));

Now as the complexity grows I want to extract each update in into it's own method:

jdbi.useHandle(handle -> handle.useTransaction(h -> {
                    var id = someQuery1(h);
                    someQuery2(id, h);
                }
        ));

...with someQuery1 looking like:

private Long someQuery1(Handle handle) {

        return  handle.createUpdate("some query")
                .executeAndReturnGeneratedKeys()
                .mapTo(Long.class).findOne().orElseThrow(() -> new IllegalStateException("No id"));
    }

Now when I refactor to the latter I get a SonarQube blocker bug on the someQuery1 handle.createUpdate stating:

Resources should be closed

Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use....*

I was under the impression, that because I'm using jdbi.useHandle (and passing the same handle to the called methods) that a callback would be used and immediately release the handle upon return. As per the jdbi docs:

Both withHandle and useHandle open a temporary handle, call your callback, and immediately release the handle when your callback returns.

Any help / suggestions appreciated.

TIA

Hurricane
  • 1,454
  • 1
  • 13
  • 31

1 Answers1

1

SonarQube doesn't know any specifics regarding JDBI implementation and just triggers by AutoCloseable/Closable not being closed. Just suppress sonar issue and/or file a feature-request to SonarQube team to improve this behavior.

Yurii Melnychuk
  • 858
  • 1
  • 5
  • 11
  • Evaluating JDBI here. I disagree this is good behavior. The object returned from `createUpdate` shouldn't be `Closeable` if it doesn't need to be closed by the caller. Surpressing a resource leak warning should be exceptional, not default for every JDBI interaction. This hit me after 15 minutes of playing with JDBI and I think it will be a deal breaker. A better way would be that `createUpdate` defers creating a prepared statement until `one` or `execute` is called. There is no need for the object that provides the fluent binding API to be `Closeable`. – john16384 Sep 30 '22 at 09:54