如何使用jOOQ

时间:2019-02-10 12:45:15

标签: sql kotlin jooq

我正在使用以下jOOQ配置:

private fun createConfiguration(dataSource: DataSource, loggerListener: JooqLoggerListener): Configuration {
    return DefaultConfiguration()
            .set(dataSource)
            .set(SQLDialect.POSTGRES_10)
            .set(DefaultExecuteListenerProvider(loggerListener))
            .set(Settings()
                    .withExecuteLogging(false) // We already use the custom [JooqLoggerListener].
                    .withParamType(ParamType.NAMED)
                    .withRenderFormatted(true)
                    .withRenderKeywordStyle(RenderKeywordStyle.UPPER)
                    .withRenderNameStyle(RenderNameStyle.LOWER))
}

withParamType(ParamType.NAMED)之外的所有设置均有效。

但是在我的自定义JooqLoggerListener中记录SQL,例如:

override fun renderEnd(ctx: ExecuteContext) {
    if (logger.isDebugEnabled) {
        val configuration = ctx.configuration()
        val newline = if (configuration.settings().isRenderFormatted) "\n" else ""
        val inlined = DSL.using(configuration).renderInlined(ctx.query())
        logger.debug("Executing query:{}{}", newline, ctx.sql())
        logger.debug("Executing query (with bind values):{}{}", newline, inlined)
    }
}

仍然打印问号:

13:41:47.472 [nioEventLoopGroup-1-3] DEBUG c.e.logging.JooqLoggerListener - Executing query:
SELECT 
  country.id, 
  country.alpha2_code, 
  country.alpha3_code, 
  country.name, 
  country.demonym, 
  country.continent_id
FROM country
WHERE country.id = ?

我原本希望这样:

WHERE country.id = :id

我的假设是否正确?或者withParamType(ParamType.NAMED)是否用于其他用途?

1 个答案:

答案 0 :(得分:2)

要使用参数名称,需要在查询中提供参数名称。

我首先有:

        return dslContext
                .selectFrom(COUNTRY)
                .where(COUNTRY.ID.eq(id))
                .fetchOneInto(Country::class.java)

更改为:

        return dslContext
                .selectFrom(COUNTRY)
                .where(COUNTRY.ID.eq(param("country_id", id)))
                .fetchOneInto(Country::class.java)

成功了!