[英]jOOQ: fetch into Map<K, List<Record2<V,W>>
Abstract query 抽象查询
select A.*, B.*, C.*
from A
left join B on B.aId = A.aId
left join C on C.cId = B.cId
Idea 理念
I want to fetch this into some object, which is grouped by A (each B has a unique C connected to it). 我想将其提取到某个对象中,该对象按A分组(每个B都连接有一个唯一的C)。 For me the most logical type of object to fetch into, would be something like Map<A, List<Record2<B,C>>. 对我来说,要提取到的对象中最逻辑的类型是Map <A,List <Record2 <B,C >>。
Code 码
I tried something like 我尝试了类似的东西
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
Background of solution 解决方案的背景
I don't want to use fetch(), because all the records would contain duplicate data of A, which I want to avoid. 我不想使用fetch(),因为所有记录都将包含A的重复数据,我想避免这样做。 I am converting it to a JSON object, where A would contain a list of B's and in which B contains the object C. To get this structure, Map<A, List<Result2<B,C>> would be perfect. 我将其转换为JSON对象,其中A将包含B的列表,而B中包含对象C。要获得此结构,Map <A,List <Result2 <B,C >>将是完美的。
You have to manually group those <B, C>
types into some data structure, eg jOOλ's Tuple2
type or also AbstractMap.SimpleEntry
您必须手动将那些<B, C>
类型分组为某种数据结构,例如jOOλ的Tuple2
类型或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)));
An alternative would be to resort to using streams and nested maps: 一种替代方法是求助于使用流和嵌套地图:
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 , so the fetchStream()
call can be omitted: jOOQ 3.11将包含ResultQuery.collect()
方法 ,因此可以省略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))));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.