Jdbi transaction - multiple methods - Resources should be closed

639 views Asked by At

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

1

There are 1 answers

1
Yurii Melnychuk On BEST ANSWER

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.