java递归生成树形结构数据
程序员文章站
2022-06-28 17:06:05
java递归生成树形结构数据,以查询省、市、区树形结构为例service层代码 @Autowired private AreaDao dao; /** * 获取省、市、区树形结构数据 */ public void getTree(int id) { Area area = dao.findAreaById(id); if (area != null) { List chil...
java递归生成树形结构数据,以查询省、市、区树形结构为例
service层代码
@Autowired
private AreaDao dao;
/**
* 获取省、市、区树形结构数据
*/
public Area getTree(int id) {
Area area = dao.findAreaById(id);
if (area != null) {
List<Area> childAreas = dao.findChildByParentId(area.getParentId());
if (CollectionUtils.isNotEmpty(childAreas)) {
area.setChildAreas(childAreas);
recursive(childAreas);
}
}
return area;
}
/**
* 递归查询数据
*/
public void recursive(List<Area> areas) {
for (Area area : areas) {
List<Area> childAreas = dao.findChildByParentId(area.getParentId());
if (CollectionUtils.isNotEmpty(childAreas)) {
area.setChildAreas(childAreas);
recursive(areas);
}
}
}
dao层sql查询代码
<select id="findAreaById" parameterType="int" resultMap="BaseResultMap">
select * from area where id = #{id}
</select>
<select id="findChildByParentId" parameterType="int" resultMap="BaseResultMap">
select * from area where parent_id = #{parentId}
</select>
实体类代码
@Data
public class Area {
@ApiModelProperty(value = "地点id")
private int areaId;
@ApiModelProperty(value = "地点名称")
private String name;
@ApiModelProperty(value = "地点父id")
private int parentId;
@ApiModelProperty(value = "下级地点")
private List<Area> childAreas;
}
本文地址:https://blog.csdn.net/oracle_a/article/details/109277057