Retrieving the value of selectCount in jooq

三世轮回 提交于 2019-12-10 13:30:45

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/14952007/retrieving-the-value-of-selectcount-in-jooq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!