在jooq中检索selectCount的值 [英] Retrieving the value of selectCount in jooq

查看:139
本文介绍了在jooq中检索selectCount的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些看起来像这样的代码:

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

但是似乎必须要有一个更好的解决方案(这是类型安全的,因为这是使用jooq的全部目的).有什么建议吗?

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?

推荐答案

不幸的是,对于此特定查询,没有很多更好"的方法来安全地键入count()值.添加类型安全性,您可以做的是:

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

问题在于,到fetch()方法到达"时,有关投影的大多数类型信息已丢失"给Java编译器. ResultQuery.fetchXXX()方法无法从SELECT子句中将其恢复并提供给您.

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.

在jOOQ用户组中,一些用户争辩说将投影完全移到fetch()方法中,完全是C#的LINQ或Scala的SLICK的方式.这将使更高级的SELECT语句的表达大大复杂化. 这里有更详细的解释.

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.

在jOOQ 3.0中,引入了附加的记录级类型安全性.因此,在jOOQ 3.3中,可以这样获取单个值(已注册为#2246 ):

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

这篇关于在jooq中检索selectCount的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆