抽象查询
select A.*, B.*, C.*
from A
left join B on B.aId = A.aId
left join C on C.cId = B.cId
观
我想把它取到一个对象,它被A分组(每个B都有一个独特的C连接到它)。对我来说,要获取的最合理的对象类型是Map< A,List< Record2< B,C>&gt ;.
代码
我试过像
using(configuration()).select(A.fields())
.select(B.fields())
.select(C.fields())
.from(A)
.leftJoin(B).on(B.aId.eq(A.aId)
.leftJoin(C).on(C.cId.eq(B.cId)
.fetchGroups(
r -> r.into(A).into(APojo.class),
r -> r.into(B).into(BPojo.class),
r -> r.into(C).into(CPojo.class)); // Goes wrong because fetchGroups only accepts 2 arguments
解决方案背景
我不想使用fetch(),因为所有记录都包含A的重复数据,我想避免。我将其转换为JSON对象,其中A将包含B的列表,并且其中B包含对象C.为了获得该结构,Map< A,List< Result2< B,C>>会是完美的。
答案 0 :(得分:3)
您必须手动将这些<B, C>
类型分组到某些数据结构中,例如jOOλ的Tuple2
type或AbstractMap.SimpleEntry
Map<APojo, List<Tuple<BPojo, CPojo>>> result =
using(configuration()).select(A.fields())
.select(B.fields())
.select(C.fields())
.from(A)
.leftJoin(B).on(B.aId.eq(A.aId))
.leftJoin(C).on(C.cId.eq(B.cId))
.fetchGroups(
r -> r.into(A).into(APojo.class),
r -> tuple(
r.into(B).into(BPojo.class),
r.into(C).into(CPojo.class)));
另一种方法是使用流和嵌套地图:
Map<APojo, Map<BPojo, CPojo>> result =
using(configuration()).select(A.fields())
.select(B.fields())
.select(C.fields())
.from(A)
.leftJoin(B).on(B.aId.eq(A.aId))
.leftJoin(C).on(C.cId.eq(B.cId))
.fetch()
.stream()
.collect(Collectors.groupingBy(
r -> r.into(A).into(APojo.class),
Collectors.toMap(
r -> r.into(B).into(BPojo.class),
r -> r.into(C).into(CPojo.class))));
jOOQ 3.11 will include a ResultQuery.collect()
method,因此fetchStream()
调用可以省略:
Map<APojo, Map<BPojo, CPojo>> result =
using(configuration()).select(A.fields())
.select(B.fields())
.select(C.fields())
.from(A)
.leftJoin(B).on(B.aId.eq(A.aId))
.leftJoin(C).on(C.cId.eq(B.cId))
.collect(Collectors.groupingBy(
r -> r.into(A).into(APojo.class),
Collectors.toMap(
r -> r.into(B).into(BPojo.class),
r -> r.into(C).into(CPojo.class))));