我正在尝试从具有“ hierCd”和“ parentHierCd”的父子关系的那个表中的一个表中获取数据列表。我第一次得到所有父母名单。在那之后,当我建立数据时,我需要得到那些父母的所有孩子。就像我在预期结果中所示,这可能是多层次的。
表中的数据如下
**hierCd** **Name** **parentHierCd**
TEA-1 tea1 TEA
TEA-2 tea2 TEA
TEA-3 tea3 TEA
TEAA-1 teaa-1 TEA-1
TEAA-2 teaa-2 TEA-1
TEAAA-1 teaaa-1 TEAA-1
ITC-1 itc-1 ITC
ITC-2 itc-2 ITC
ITCA-1 itca-1 ITC-1
ITCA-2 itca-2 ITC-1
我提到了所有代码。 层是实体文件,是从数据库映射的。 委员会正在使用其余api设置数据。
//Committee api model class
public class Committee {
@JsonProperty("id")
private UUID id = null;
@JsonProperty("name")
private String name = null;
@JsonProperty("code")
private String code = null;
@JsonProperty("parentCd")
private String parentCd = null;
@JsonProperty("children")
@Valid
private List<Committee> children = null;
with getters and setters
}
//Hier entity model class
public class Hier {
private String hierCd;
private String hierTyp;
private String hierName;
private String uuid;
private String parentHierCd;
with getters and setters
}
//This method is calling for get parent record.
public List<Committee> getCommittees(){
private List<String> PARENT_CDS = Arrays.asList(new String[] { "TEA", "ITC" });
List<Committee> committees = new ArrayList<>();
List<Hier> committeeHierarchies = committeeRepository.findParentHiersByHierCdInOrderByHierNameAsc(PARENT_CDS);
for(Hier hier:committeeHierarchies)
{
committees.add(committeeBuilder(hier));
}
return committees;
}
// Building committee with sub committee
private Committee committeeBuilder(Hier hier) {
Committee committee = new Committee();
committee.setId(UUID.fromString(hier.getUuid()));
committee.setCode(hier.getHierCd());
committee.setName(hier.getHierName());
committee.setParentCd(hier.getParentHierCd());
if(hiertype.equals("allCommittee")){
committee.setChildren(getChildrenByParentCd(hier.getHierCd()));
}
return committee;
}
//Return sub committees by parent hier code
public List<Committee> getChildrenByParentCd(String parentCd) {
List<Committee> committees = new ArrayList<>();
List<Hier> children = committeeRepository.findChildrenByParentHierCd(parentCd);
for (Hier hier : children) {
Committee committee = new Committee();
committee.setId(UUID.fromString(hier.getUuid()));
committee.setCode(hier.getHierCd());
committee.setName(hier.getHierName());
committee.setParentCd(hier.getParentHierCd());
committees.add(committee);
}
return committees;
}
上面的代码像下面这样返回,它只将数据返回到两个级别(父级和子级)中,但是我需要像下面提到的那样以递归的方式获取数据。
> TEA
> TEA-1
> TEA-2
> TEA-3
> ITC
> ITC-1
> ITC-2
结果应如下所示
> TEA
> TEA-1
> TEAA-1
> TEAAA-1
> TEAA-2
> TEA-2
> TEA-3
> ITC
> ITC-1
> ITCA-1
> ITCA-2
> ITC-2
答案 0 :(得分:0)
使用递归函数方法来解决此问题。就像需要查找子孩子是否可用于父对象。基于该叫委员会的Builder