实体类:
private String dspId;
private String parentId; //父类id
private String dataName;
private Integer sortingNumber;
private String remarks;
private Date createTime;
private Date updateTime;
private Date deleteTime;
private Integer dataFlag;
private Integer anId;
private Integer isParent;//是否有父类
private List<DataSpecies> chlidSpecies;
dao层和接口使用mybatis逆向生成,这里就不住解释.
service层:
public List<DataSpecies> findDataspecies() {
// TODO Auto-generated method stub
//查询所有的结果
DataSpeciesExample example = new DataSpeciesExample();
Criteria criteria = example.createCriteria();
criteria.andDataFlagEqualTo(0);
List<DataSpecies> dataSpecies = dataspeciesMapper.selectByExample(example);
//创建最后的结果 想最后结果填充数据
List<DataSpecies> dataSpeciesList= new ArrayList<>();
for (DataSpecies species : dataSpecies) {
if(StringUtils.isBlank(species.getParentId()) ){
//一级菜单没有ParentId
dataSpeciesList.add(species);
}
}
//为一级菜单设计子菜单 使用getchild递归
for (DataSpecies daSpecies : dataSpeciesList) {
daSpecies.setChlidSpecies(getChild(daSpecies.getDspId(),dataSpecies));//这里getchild方法是递归
}
return dataSpeciesList;
}
//递归方法:
public List<DataSpecies> getChild(String id,List<DataSpecies> rootDataSpecies){
//创建子菜单
List<DataSpecies> speciesList = new ArrayList<>();
for (DataSpecies dataSpecies : rootDataSpecies) {
//遍历蓑鲉节点 ,将父类id与传过来的id进行对比
if(StringUtils.isNotBlank(dataSpecies.getParentId())){
if(dataSpecies.getParentId().equals(id)){
speciesList.add(dataSpecies);
}
}
}
//把子菜单循环遍历
for (DataSpecies childSpecies : speciesList) {
if(childSpecies.getIsParent()==1){
childSpecies.setChlidSpecies(getChild(childSpecies.getDspId(),rootDataSpecies));
}
}
if(speciesList.size()==0){
return null;
}
return speciesList;
}
web层直接调用service 的方法就行,这里不做说明.
来源:https://www.cnblogs.com/guotao123/p/8818108.html