网上的具体代码实现如下:
@RequestMapping("getTree")
public Map<String, Object> getTree(int id) {
Map<String, Object> map = new HashMap<>();
try {
ChinaCitys province = dao.findProvince(id); //查询出一个省
if (province != null) {
List<ChinaCitys> citys = dao.findChildren(province.getId());//查询省下面的所有市
digui(citys); //调用递归算法查询市以下的区县
province.setChildren(citys);
}
map.put("data", province);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public void digui(List<ChinaCitys> citys) {
List<ChinaCitys> retList = new ArrayList<>();
for (ChinaCitys c : citys) {
retList = dao.findChildren(c.getId());
if (retList.size() > 0) {
c.setChildren(retList);
digui(retList); //循环调用自己
}
}
}
sql语句:
<select id="findProvince" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select id,name from china_citys
WHERE id = #{id}
</select>
<select id="findChildren" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select id,name from china_citys
WHERE upid = #{id}
</select>
个人实际操作:
public List<AppExamDeptVo> getExamDeptTree() {
List<AppExamDeptVo> appExamDeptVoList = new ArrayList<>();
try {
appExamDeptVoList = ntClient.appExamDeptService.selectAll(0L);
for (AppExamDeptVo ae : appExamDeptVoList) {
List<AppExamDeptVo> aed = ntClient.appExamDeptService.selectAll(ae.getDeptId());
digui(aed);
ae.setChildren(aed);
}
} catch (Exception e) {
}
return appExamDeptVoList;
}
public void digui(List<AppExamDeptVo> aed) {
List<AppExamDeptVo> retList = new ArrayList<>();
for (AppExamDeptVo c : aed) {
retList = ntClient.appExamDeptService.selectAll(c.getDeptId());
if (retList.size() > 0) {
c.setChildren(retList);
digui(retList); //循环调用自己
}
}
}
SQL语句:
<!--查询组织机构-->
<select id="selectAll" parameterType="java.lang.Long" resultMap="AppExamDeptResult">
<include refid="selectAppExamDeptVo"/>
where parent_id = #{deptId}
</select>