我在postgres數據庫中有以下記錄。 parent_pk與父子關係中的pk相關。 pk = 1是所有孩子的直接和間接的父母。從深層遞歸父子關係構建JSON
pk name type parent_pk
--- ---- ---- ---------
1 hnumber101 house 1
2 hnumber201 house 1
791 dodge_charger vehicle 1
801 mustang vehicle 791
595020 civic vehicle 2
10077661099 john user 10046725614
10046725614 mesto dev 1
801 shen house 791
44444444 crep house 10046725614
22222222 keper user 10046725614
11111111 show house 10046725614
84257651 shen house 801
11 lemp house 2
我想生成以下格式 -
{
"children" : [
{ "pk" : "1", "name" : "hnumber101", "children" : [
{ "pk" : "10046725614", "name" : "mesto", "children" : [
{ "pk" : "10077661099", "name" : "john", "children" : [] },
{ "pk" : "44444444", "name" : "crep", "children" : [] },
{ "pk" : "22222222", "name" : "keper", "children" : [] },
{ "pk" : "11111111", "name" : "show", "children" : [] }
] }
] },
{ "pk" : "791", "name" : "dodge_charger", "children" : [
{ "pk" : "801", "name" : "mustang", "children" : [
{ "pk" : "84257651", "name" : "shen", "children" : [
] }
] },
{ "pk" : "2", "name" : "hnumber201", "children" : [
{ "pk" : "595020", "name" : "civic", "children" : [] },
{ "pk" : "11", "name" : "lemp", "children" : [] }
] }
] }
] }
]
}
一個JSON出上述與我目前的代碼,我可以能夠得到的只有PK = 1的孩子的孩子。 但深層遞歸沒有發生。
Collection<GatherEntity> gatherEntityChildren= gatherManager.findByParentGatherId(1);
getRecursiveGatherFromParent(gatherEntityChildren, gatherListParent);
private List<Gather> getRecursiveGatherFromParent(Collection<GatherEntity> gatherEntityChildren, List<Gather> gatherListParent) throws JSONException {
if(gatherEntityChildren != null && gatherEntityChildren.size() > 0) {
for (Iterator<gatherEntity> iterator = gatherEntityChildren.iterator(); iterator.hasNext();) {
GatherEntity gatherEntity = (GatherEntity) iterator.next();
Gather gather = getGatherFromEntity(gatherEntity);
List<Gather> gatherChildren = populateGatherAndChild(gatherEntity);
gather.setChildren(new HashSet<Gather>(gatherChildren));
gatherListParent.add(gather);
}
}
return gatherListParent;
}
private List<Gather> populateGatherAndChild(GatherEntity gatherEntity) {
Collection<GatherEntity> gatherEntityChildren= gatherManager.findByParentGatherId(gatherEntity.getGatherId());
List<Gather> gatherList = gatherEntityChildren.stream().map(UserAPIImpl::getGatherFromEntity).collect(Collectors.toList());
return gatherList;
}
private static Gather getGatherFromEntity(GatherEntity gatherEntity) {
Gather gather = new Gather();
gather.setGatherId(gatherEntity.getGatherId());
gather.setName(gatherEntity.getName());
return gather;
}
我不知道您是否有興趣;但是對於純粹的PostgreSQL解決方案,請參閱http://stackoverflow.com/a/25683134/1499698 – pozs