1.适用场景: 不知道树的深度(for 循环不知道遍历几次,或者每个根的遍历次数不一样)
1. 主要是以下三个字段
建表语句:
-- auto-generated definition
create table sys_region
(
id int auto_increment comment '地区主键编号'
primary key,
name text null comment '地区名称',
short_name text null comment '简称',
code varchar(5000) null comment '行政地区编号',
parent_code varchar(5000) null comment '父id',
level int null comment '1级:省、直辖市、自治区
2级:地级市
3级:市辖区、县(旗)、县级市、自治县(自治旗)、特区、林区
4级:镇、乡、民族乡、县辖区、街道
5级:村、居委会',
flag int null comment '0:正常 1废弃'
)
comment '地区表' charset=utf8;
xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.RegionMapper" >
<resultMap id="BaseResultMap" type="com.example.demo.entity.Region">
<result column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="code" property="code" jdbcType="VARCHAR" />
<result column="parent_code" property="parentCode" jdbcType="VARCHAR"/>
<result column="level" property="level" jdbcType="INTEGER"/>
</resultMap>
<select id="list" resultMap="BaseResultMap">
select id, name ,code ,parent_code ,level from sys_region
</select>
</mapper>
mapper 接口
import com.example.demo.entity.Region;
import java.util.List;
/**
* @program: springboot_01
* @description:
* @author: guoyiguang
* @create: 2021-01-14 14:42
**/
//@Repository 用MapperScan 代替每个mapper接口上面的 Repository
public interface RegionMapper {
List<Region> list();
}
service 层代码:
@Override
public List<Region> recursionRegion() {
List<Region> regionListFromDb = regionMapper.list();
// 获取根
List<Region> rootList = regionListFromDb.stream()
.filter(root -> null == root.getParentCode())
.collect(Collectors.toList());
for (Region root: rootList) {
recursionRegion(root, regionListFromDb);
}
return rootList;
}
/**
* @Description:
* @Param: target 非最后一层;regionListFromDb 源数据
* @return: target 的下一级集合
* @Date:
*/
private List<Region> recursionRegion(Region target ,List<Region> regionListFromDb){
// 最底层 ,当目标 层级是 4 的时候,结束递归
if (target.getLevel() == 4) {
return new ArrayList<>() ;
}
// 获取下一级
List<Region> cityList = regionListFromDb.stream()
.filter(son -> null != son.getParentCode() && son.getParentCode().equalsIgnoreCase(target.getCode()))
.collect(Collectors.toList());
target.setChildren(cityList);
for (Region city2 : cityList) {
List<Region> city3List = recursionRegion(city2, regionListFromDb);
city2.setChildren(city3List);
}
return cityList;
}
写个controller 测试
@RequestMapping("/recursionRegion")
@ResponseBody
public List<Region> recursionRegion(){
List<Region> list = regionService.recursionRegion();
return list;
}