逻辑是一开始查出根节点,然后一层层循环添加子节点
package com.service.system;
import com.alibaba.fastjson.JSONObject;
import com.dao.mybatis.CompanyMybatisDao;
import com.entity.database.CompanyEntity;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
public class CompanyService {
@Resource
private CompanyMybatisDao companyMybatisDao;
public JSONObject selectAll(CompanyEntity companyEntity) {
JSONObject json = new JSONObject();
/*查询出所有的数据*/
List<CompanyEntity> treeData = companyMybatisDao.selectCompanyTrees(companyEntity);
var departmentDtos = new ArrayList<CompanyEntity>();
var departmentDtos2 = new ArrayList<CompanyEntity>();
for (var t : treeData) {
t.setChildren(childrenDepartTree(companyMybatisDao, t.getId()));
departmentDtos.add(t);
}
/*进行树形结构封装*//*id 指的最大的id 0 滨投 company 指这条数据*/
if (companyEntity.getVagueName() != null) {
List<CompanyEntity> companyEntities = childrenDepartTree2(departmentDtos, companyEntity.getVagueName(),departmentDtos2);
json.put("data", companyEntities);
} else {
json.put("data", departmentDtos);
}
json.put("msg", "查询部门成功");
json.put("code", 0);
return json;
}
public static List<CompanyEntity> childrenDepartTree(CompanyMybatisDao companyMybatisDao, Integer id) {
var param = new CompanyEntity();
param.setParentId(id);
var entity = companyMybatisDao.selectCompanyTrees(param);
for (var e : entity) {
e.setChildren(childrenDepartTree(companyMybatisDao, e.getId()));
}
return entity;
}
public static List<CompanyEntity> childrenDepartTree2(List<CompanyEntity> departmentDtos, String vagueName,List<CompanyEntity> departmentDtos2) {
int i = 0;
for (CompanyEntity a : departmentDtos
) {
int i1 = a.getName().indexOf(vagueName);
if (i1 == -1 &&a.getChildren()!=null) {
childrenDepartTree2(a.getChildren(),vagueName,departmentDtos2);
}else {
departmentDtos2.add(a);
}
}
return departmentDtos2;
}
}
后来又加了模糊查询
字段VagueName;
以模糊字段为根节点,的树状查询