拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 jOOQ中的计数查询

jOOQ中的计数查询

白鹭 - 2021-11-24 509 0 0

1.概述

在本教程中,我们将演示如何使用jOOQ面向对象查询(也称为jOOQ)执行计数查询。 jOOQ是一个流行的Java数据库库,可帮助您用Java编写类型安全的SQL查询。

2. jOOQ

jOOQ是ORM替代方案。与大多数其他ORM不同, jOOQ以关系模型为中心,而不是以领域模型为中心。例如,Hibernate帮助我们编写Java代码,然后将其自动转换为SQL。但是,jOOQ允许我们使用SQL在数据库中创建关系对象,然后它生成Java代码以映射到那些对象。

3. Maven依赖

在本教程中,我们将需要jooq

< dependency >

 < groupId > org.jooq </ groupId >

 < artifactId > jooq </ artifactId >

 < version > 3.14.8 </ version >

 </ dependency >

4.计数查询

假设我们的数据库中有一个author author表包含一个id, first_name, and last_name.

运行计数查询可以通过几种不同的方式来完成。

4.1 fetchCount

DSL.fetchCount具有多种方法来计算表中的记录数。

首先,让我们看一下**fetchCount ​(Table<?> table)**方法来计算记录数:

int count = dsl.fetchCount(DSL.selectFrom(AUTHOR));

 Assert.assertEquals(3, count);

接下来,让我们尝试使用带有selectFrom方法和where **fetchCount ​(Table<?> table)**方法来计算记录数:

int count = dsl.fetchCount(DSL.selectFrom(AUTHOR)

 .where(AUTHOR.FIRST_NAME.equalIgnoreCase("Bryan")));

 Assert.assertEquals(1, count);

现在,让我们尝试**fetchCount ​(Table<?> table, Condition condition)**方法来计算的记录数:

int count = dsl.fetchCount(AUTHOR, AUTHOR.FIRST_NAME.equalIgnoreCase("Bryan"));

 Assert.assertEquals(1, count);

我们还可以对多个条件**fetchCount ​(Table<?> table, Collection<? extends Condition> conditions)**

Condition firstCond = AUTHOR.FIRST_NAME.equalIgnoreCase("Bryan");

 Condition secondCond = AUTHOR.ID.notEqual(1);

 List<Condition> conditions = new ArrayList<>();

 conditions.add(firstCond);

 conditions.add(secondCond);

 int count = dsl.fetchCount(AUTHOR, conditions);

 Assert.assertEquals(1, count);

在这种情况下,我们将过滤条件添加到列表中,并将其提供给fetchCount方法。

fetchCount方法还允许在多个条件下使用varargs:

Condition firstCond = AUTHOR.FIRST_NAME.equalIgnoreCase("Bryan");

 Condition secondCond = AUTHOR.ID.notEqual(1);

 int count = dsl.fetchCount(AUTHOR, firstCond, secondCond);

 Assert.assertEquals(1, count);

4.2 count

让我们尝试使用count方法来获取可用记录的数量:

int count = dsl.select(DSL.count()).from(AUTHOR)

 .fetchOne(0, int.class);

 Assert.assertEquals(3, count);

4.3 selectCount

现在,让我们尝试使用selectCount方法获取可用记录的计数:

int count = dsl.selectCount().from(AUTHOR)

 .where(AUTHOR.FIRST_NAME.equalIgnoreCase("Bryan"))

 .fetchOne(0, int.class);

 Assert.assertEquals(1, count);

4.4 简单select

我们也可以使用简单的select 获取可用记录数的方法:

int count = dsl.select().from(AUTHOR).execute();

 Assert.assertEquals(3, count);

4.5 用groupBy

让我们尝试使用selectcount方法来查找按字段分组的记录数:

Result<Record2<String, Integer>> result = dsl.select(AUTHOR.FIRST_NAME, DSL.count())

 .from(AUTHOR).groupBy(AUTHOR.FIRST_NAME).fetch();

 Assert.assertEquals(3, result.size());

 Assert.assertEquals(result.get(0).get(0), "Bert");

 Assert.assertEquals(result.get(0).get(1), 1);

5.结论

在本文中,我们研究了如何在jOOQ中执行计数查询。

我们已经研究了使用selectCount, count, fetchCount, select,countgroupBy方法来对记录数进行计数。

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *