jOOQ fetchGroups不会为一对多关系返回空集合



对于一对多关系,我有以下查询。

return create.select(Parent.asterisk(), Child.asterisk())
.from(PARENT)
.leftJoin(CHILD)
.onKey()
.where(myCondition)
.fetchGroups(ParentRecord.class, ChildRecord.class);

当没有子记录时,我不会得到一个空列表。总是有一个子记录的所有字段都设置为null。

[Child(id=null, name=null)]

防止这些空记录被返回的最佳方法是什么?

这是一个流行的用例,所以我在这里写了关于jOOQ的API这一部分的博客。

您可以使用自己的收集器:

Map<ParentRecord, List<ChildRecord>> result =
create.select(PARENT.asterisk(), CHILD.asterisk())
.from(PARENT)
.leftJoin(CHILD).onKey()
.where(myCondition)
.collect(groupingBy(
r -> r.into(PARENT), filtering(
r -> r.get(CHILD.ID) != null, mapping(
r -> r.into(CHILD), toList()
)
)
));

我假设这些静态导入:

import static java.util.stream.Collectors.*;
import static org.jooq.impl.DSL.*;
import static com.example.generated.Tables.*;

这是一个常见的问题。改进当前的API可能是有意义的:https://github.com/jOOQ/jOOQ/issues/11888

最新更新