jOOQ:获取Map <k,list <record2 <v,w =“”>&gt;

时间:2018-05-05 18:44:03

标签: java jooq

抽象查询

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&lt; A,List&lt; Record2&lt; B,C&gt;&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&lt; A,List&lt; Result2&lt; B,C&gt;&gt;会是完美的。

1 个答案:

答案 0 :(得分:3)

您必须手动将这些<B, C>类型分组到某些数据结构中,例如jOOλ的Tuple2 typeAbstractMap.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))));