Here is the Scenario, I have 5 tables having one to many relations with each other, I have to map result data in hierarchical manner in below given Pojos with Jooq.
DB Tables are a, b, c, d, e
// Here are response Pojo's
Class APojo {
public string name;
public List<BPojo> listOfB;
}
Class BPojo {
public string name;
public List<CPojo> listOfC;
}
Class CPojo {
public string name;
public List<DPojo> listOfD;
}
Class DPojo {
public string name;
public List<EPojo> listOfE;
}
Class EPojo {
public string name;
}
Expected sample response
{
"name":"A1",
"list_of_b":[
{
"name":"A1B1",
"list_of_c":[
{
"name":"A1B1C1",
"list_of_d":[
{
"name":"A1B1C1D1",
"list_of_e":[
{
"name":"A1B1C1D1E1"
},
{
"name":"A1B1C1D1E2"
}
]
},
{
"name":"A1B1C1D2",
"list_of_e":[
{
"name":"A1B1C1D2E1"
},
{
"name":"A1B1C1D2E2"
}
]
}
]
},
{
"name":"A1B1C2",
"list_of_d":[
{
"name":"A1B1C2D1",
"list_of_e":[
{
"name":"A1B1C2D1E1"
},
{
"name":"A1B1C2D1E2"
}
]
},
{
"name":"A1B1C2D2",
"list_of_e":[
{
"name":"A1B1C2D2E1"
},
{
"name":"A1B1C2D2E2"
}
]
}
]
}
]
},
{
"name":"A1B2",
"list_of_c":[
{
"name":"A1B2C1",
"list_of_d":[
{
"name":"A1B2C1D1",
"list_of_e":[
{
"name":"A1B1C1D1"
},
{
"name":"A1B1C1D2"
}
]
},
{
"name":"A1B2C1D2",
"list_of_e":[
{
"name":"A1B1C1D1"
},
{
"name":"A1B1C1D2"
}
]
}
]
},
{
"name":"A1B2C2",
"list_of_d":[
{
"name":"A1B2C2D1",
"list_of_e":[
{
"name":"A1B1C1D1"
},
{
"name":"A1B1C1D2"
}
]
},
{
"name":"A1B2C2D2",
"list_of_e":[
{
"name":"A1B1C1D1"
},
{
"name":"A1B1C1D2"
}
]
}
]
}
]
}
]
}
I tried something like this first but It did not work because fetch groups only accepts 2 arguments
using(configuration()).select(A.fields())
.select(B.fields())
.select(C.fields())
.select(D.fields())
.select(E.fields())
.from(A)
.join(B).on(A.ID.eq(B.A_ID)
.join(C).on(B.ID.eq(C.B_ID)
.join(D).on(C.ID.eq(D.C_ID)
.join(E).on(D.ID.eq(E.D_ID)
.fetchGroups(
r -> r.into(A).into(APojo.class),
r -> r.into(B).into(BPojo.class),
r -> r.into(C).into(CPojo.class),
r -> r.into(D).into(DPojo.class),
r -> r.into(E).into(EPojo.class)
);
Then I got this post and tried it as given below and other 2 method given in the post, but this also did not worked because Collectors.toMap
accepts only 2 arguments and I have to fetch 5 level hierarchical data.
using(configuration()).select(A.fields())
.select(B.fields())
.select(C.fields())
.select(D.fields())
.select(E.fields())
.from(A)
.join(B).on(A.ID.eq(B.A_ID)
.join(C).on(B.ID.eq(C.B_ID)
.join(D).on(C.ID.eq(D.C_ID)
.join(E).on(D.ID.eq(E.D_ID)
.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)
r -> r.into(D).into(DPojo.class)
r -> r.into(E).into(EPojo.class)
)));