Jdbi 事务 - 多种方法 - 应该关闭资源
Jdbi transaction - multiple methods - Resources should be closed
假设我想在交易中 运行 两个 sql 查询我有如下代码:
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();
}
));
现在随着复杂性的增加,我想将每个更新提取到它自己的方法中:
jdbi.useHandle(handle -> handle.useTransaction(h -> {
var id = someQuery1(h);
someQuery2(id, h);
}
));
...someQuery1
看起来像:
private Long someQuery1(Handle handle) {
return handle.createUpdate("some query")
.executeAndReturnGeneratedKeys()
.mapTo(Long.class).findOne().orElseThrow(() -> new IllegalStateException("No id"));
}
现在,当我重构为后者时,我在 someQuery1 handle.createUpdate
上收到一个 SonarQube 阻止程序错误,说明:
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....*
我的印象是,因为我正在使用 jdbi.useHandle
(并将 same 句柄传递给被调用的方法),所以会使用回调,并且return 后立即松开手柄。根据 jdbi docs:
Both withHandle and useHandle open a temporary handle, call your
callback, and immediately release the handle when your callback
returns.
感谢任何帮助/建议。
TIA
SonarQube 不知道有关 JDBI
实施的任何细节,只是通过 AutoCloseable
/Closable
未关闭触发。只需抑制声纳问题 and/or 向 SonarQube 团队提交 feature-request 以改进此行为。
假设我想在交易中 运行 两个 sql 查询我有如下代码:
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();
}
));
现在随着复杂性的增加,我想将每个更新提取到它自己的方法中:
jdbi.useHandle(handle -> handle.useTransaction(h -> {
var id = someQuery1(h);
someQuery2(id, h);
}
));
...someQuery1
看起来像:
private Long someQuery1(Handle handle) {
return handle.createUpdate("some query")
.executeAndReturnGeneratedKeys()
.mapTo(Long.class).findOne().orElseThrow(() -> new IllegalStateException("No id"));
}
现在,当我重构为后者时,我在 someQuery1 handle.createUpdate
上收到一个 SonarQube 阻止程序错误,说明:
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....*
我的印象是,因为我正在使用 jdbi.useHandle
(并将 same 句柄传递给被调用的方法),所以会使用回调,并且return 后立即松开手柄。根据 jdbi docs:
Both withHandle and useHandle open a temporary handle, call your callback, and immediately release the handle when your callback returns.
感谢任何帮助/建议。
TIA
SonarQube 不知道有关 JDBI
实施的任何细节,只是通过 AutoCloseable
/Closable
未关闭触发。只需抑制声纳问题 and/or 向 SonarQube 团队提交 feature-request 以改进此行为。