Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving the value of selectCount in jooq

Tags:

java

sql

jooq

I have some code that looks like this:

Record record = jooq
    .selectCount()
    .from(USERS)
    .fetchOne();

Currently I'm doing the following to get the count:

Integer count = (Integer) record.getValue(0);

But it seems like there must be a better solution (that's type-safe...since that's the whole point of using jooq). Any suggestions?

like image 379
jorlow Avatar asked Feb 19 '13 07:02

jorlow


1 Answers

Unfortunately, for this particular query, there aren't many "better" ways to typesafely get the count() value. What you could do, to add type-safety, is this:

Field<Integer> f = count();
Integer count = jooq.
    .select(f) // Or selectCount(). Replaced it to illustrate the case
    .from(USERS)
    .fetchOne(f);

The problem is that most of the type information about the projection has been "lost" to the Java compiler, by the time the fetch() methods are "reached". There is no way that a ResultQuery.fetchXXX() method could recover it from the SELECT clause, and produce it to you.

On the jOOQ user group, some users have argued to move the projection into the fetch() methods, entirely, the way C#'s LINQ, or Scala's SLICK do it. This would greatly complicate the expression of more advanced SELECT statements. An more elaborate explanation is documented here.

With jOOQ 3.0, additional record-level typesafety has been introduced. In jOOQ 3.3, it will thus be possible to fetch a single value as such (has been registered as #2246):

<T> T fetchValue(Select<Record1<T>> select);
like image 155
Lukas Eder Avatar answered Nov 06 '22 23:11

Lukas Eder