jOOQ fetch vs fetchResultSet并在Kotlin中关闭连接 [英] jOOQ fetch vs fetchResultSet and close connection in Kotlin
问题描述
我正在将Kotlin与HikariCP和jOOQ一起用于查询我的数据库.我已经意识到该代码可以按预期工作,然后获取行并随后关闭连接:
I'm using Kotlin with HikariCP and jOOQ to query my database. I've come to realize that this code works as expected, fetching the rows and closing the connection afterwards:
class CountriesService(private val datasource: DataSource) {
private val countries = Countries()
fun getCountries(): List<String> {
DSL.using(datasource, SQLDialect.POSTGRES_10)
.use { ctx ->
ctx.select(countries.CO_NAME)
.from(countries)
.orderBy(countries.CO_NAME)
.fetch()
return emptyList()
}
}
}
而如果我使用fetchResultSet()
,则连接永远不会关闭,并且池会变干:
whereas if I use fetchResultSet()
, the connection is never closed and the pool dries out:
class CountriesService(private val datasource: DataSource) {
private val countries = Countries()
fun getCountries(): List<String> {
DSL.using(datasource, SQLDialect.POSTGRES_10)
.use { ctx ->
ctx.select(countries.CO_NAME)
.from(countries)
.orderBy(countries.CO_NAME)
.fetchResultSet()
return emptyList()
}
}
}
我已经看到AbstractResultQuery#fetchResultSet()
委托给fetchLazy()
方法,所以不确定是否与此有关.
I've seen that AbstractResultQuery#fetchResultSet()
is delegating to a fetchLazy()
method, so not sure if it has something to do with that.
如果我自己获得连接,而不是将其委托给DSLContext
,那么它将起作用:
If I get the connection myself instead of delegating it to the DSLContext
, then it works:
class CountriesService(private val datasource: DataSource) {
private val countries = Countries()
fun getCountries(): List<String> {
val conn = datasource.connection
conn.use {
DSL.using(it, SQLDialect.POSTGRES_10)
.select(countries.CO_NAME)
.from(countries)
.orderBy(countries.CO_NAME)
.fetchResultSet()
return emptyList()
}
}
}
这是我应该使用的最后一种方法吗?
Is this last approach the one I should be using?