How to use Scala's String Interpolation in jOO

2019-08-08 15:59发布

问题:

I would like to use the string interpolation feature of jOOQ in Scala, for example resultQuery"SELECT * FROM objects":

// setup connection
val con = DriverManager.getConnection(url, userName, password)

// create DSLContext
val dsl = DSL.using(con, SQLDialect.POSTGRES_9_4)

// normal use of DSLContext
dsl.resultQuery("SELECT * FROM objects")

// intented use of string interpolation
val q = resultQuery"SELECT * FROM objects"

val result = q.fetch()
println(result)

Running this code (without any outside configuration and the like) results in the following exception:

Exception in thread "main" org.jooq.exception.DetachedException: Cannot execute query. No Connection configured
    at org.jooq.impl.AbstractQuery.execute(AbstractQuery.java:312)
    at org.jooq.impl.AbstractResultQuery.fetch(AbstractResultQuery.java:305)
    ...

It seems that the SQLInterpolation is using the default settings. I tried to provide these settings by setting DSLContext as well as Configuration as implicits but I still received the same exception:

implicit val dsl = DSL.using(con, SQLDialect.POSTGRES_9_4)
implicit val config = new DefaultConfiguration().derive(con)
                                                .derive(SQLDialect.POSTGRES_9_4)

How do I correctly provide my settings (connection, dialect, etc.) to the string interpolation?

回答1:

The ResultQuery object that you've created using string interpolation is not "attached", i.e. it cannot be executed on its own.

In other words, you should run the query like this, instead:

val result = dsl.fetch(q)


标签: scala jooq