gpt4 book ai didi

java - 如何在 jooq 中选择一个自动生成的记录和附加数据?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:46:23 25 4
gpt4 key购买 nike

假设您有两个表,foobar和匹配 foo 的表格允许 bar小号:

foo             bar
+----+-------+ +----+-------+
| id |fooName| | id |barName|
+------------+ +----+-------+
| 1 | aa | | 10 | xx |
| 2 | bb | | 11 | yy |
| 3 | cc | | 12 | zz |
+------------+ +----+-------+

n:m foo 之间的关系和 bar

foo_x_bar
+--------+--------+
| foo_id | bar_id |
+-----------------+
| 1 | 10 |
| 1 | 11 |
| 2 | 11 |
| 3 | 12 |
+-----------------+

现在,给定任何foo.id (比如说 1 )我想要一个 all bar 的列表s 以及它们是否适用于 foo.id 1 .我可以用这个 SQL 来做到这一点:

SELECT bar.id, bar.barName, foo_x_bar.foo_id 
FROM bar LEFT OUTER JOIN foo_x_bar
ON bar.id = foo_x_bar.bar_id AND foo_x_bar.foo_id = 1;

这给了我以下结果:

+--------+-------------+------------------+
| bar.id | bar.barName | foo_x_bar.foo_id |
+--------+-------------+------------------+
| 10 | xx | 1 |
| 11 | yy | 1 |
| 12 | zz | null |
+--------+-------------+------------------+

即:我得到了 bar 的完整列表s 并知道它们是否被 foo 引用与 id 1 . (不引用所有带有 null 的行 foo_id)

现在(终于)回答我的问题:如何使用 jooq 实现这一点,所以我得到了很好的 BarRecord jooq 类为我自动生成。这是我得到的结果:

List<Record3<Long, String, Long>> result = 
create.select(BAR.ID, BAR.BARNAME, FOO_X_BAR.FOO_ID)
.from(BAR).leftOuterJoin(FOO_X_BAR)
.on(BAR.ID.eq(FOO_X_BAR.BAR_ID))
.and(FOO_X_BAR.FOO_ID.eq(fooId))
.fetch();

一切都很好,但是如果 Bar碰巧有更多的列,这变得乏味,我想使用 BarRecord class jooq 为我自动生成。

我怎样才能得到 Record2<BarRecord, Long>相反?

===============编辑==============

根据下面的正确答案,这是我们得出的完整代码:

public static class BarMapper 
implements RecordMapper<Record, Pair<BarRecord, Boolean>> {
//the boolean indicates if a matching FOO is present
return new Pair<BarRecord, Boolean>(
record.into(BAR),
record.getValue(FOO_X_BAR.FOO_ID) != null);
}

public List<Pair<BarRecord, Boolean>> selectBarsForFooId(final long fooId) {
create.select(BAR.fields()).select(FOO_X_BAR.FOO_ID)
.from(BAR).leftOuterJoin(FOO_X_BAR)
.on(BAR.ID.eq(FOO_X_BAR.BAR_ID))
.and(FOO_X_BAR.FOO_ID.eq(fooId))
.fetch(new BarMapper());
}

最佳答案

你可以这样写:

create.select(BAR.fields())
.select(FOO_X_BAR.FOO_ID)

BAR.fields() 与 SQL 中的 BAR.* 大致相同。

您目前(从 jOOQ 3.4 开始)无法通过 jOOQ API 在您的结果中生成嵌套记录。这是一个待处理的功能请求:

为了将(部分)记录映射到类型良好的 BarRecord 中,您可以简单地调用 Record.into(Table)

BarRecord bar = Record.into(BAR);

关于java - 如何在 jooq 中选择一个自动生成的记录和附加数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26716493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com