树形结构是一个比较常用的数据类型,一般多用于查询包含父子类关系的数据。这次以一个简单的地域信息,通过jdk1.8新特性lamda来进行处理,就比较方便处理的,主要还是采用了递归思想。
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for area
-- ----------------------------
DROP TABLE IF EXISTS `area`;
CREATE TABLE `area` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'PK',
`area_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '地区名称',
`parent_id` int(11) NOT NULL COMMENT '父Id',
`sort` int(11) NULL DEFAULT NULL COMMENT '排序',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 16 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '地区表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of area
-- ----------------------------
INSERT INTO `area` VALUES (1, '广东省', 0, 1);
INSERT INTO `area` VALUES (2, '深圳市', 1, 1);
INSERT INTO `area` VALUES (3, '广州市', 1, 2);
INSERT INTO `area` VALUES (4, '湖南省', 0, 2);
INSERT INTO `area` VALUES (5, '长沙市', 4, 1);
INSERT INTO `area` VALUES (6, '株洲市', 4, 2);
INSERT INTO `area` VALUES (7, '湖北省', 0, 3);
INSERT INTO `area` VALUES (8, '武汉市', 7, 1);
INSERT INTO `area` VALUES (9, '汉口区', 8, 1);
INSERT INTO `area` VALUES (10, '汉阳区', 8, 2);
INSERT INTO `area` VALUES (11, '武昌区', 8, 3);
INSERT INTO `area` VALUES (12, '鄂州市', 7, 2);
INSERT INTO `area` VALUES (13, '鄂城区', 12, 1);
INSERT INTO `area` VALUES (14, '华容区', 12, 2);
INSERT INTO `area` VALUES (15, '梁子湖区', 12, 3);
SET FOREIGN_KEY_CHECKS = 1;
/**
* 实体类
*/
@Data
public class Area {
private Integer id;
private String areaName;
private Integer parentId;
private Integer sort;
// 封装的子类集合
private List<Area> childrenList;
}
// 查询所有地域信息
List<Area> getAllArea(Area area);
<!--根据父id获取子节点-->
<select id="getAllArea" resultMap="areaColumnMap" parameterType="Integer">
select id ,area_name ,parent_id,sort from area
</select>
@Test
public void getAllArea(){
Area area = new Area();
List<Area> areaList = areaService.getAllArea(area);
//2、组装树形结构
List<Area> newList = areaList.stream()
.filter(t -> t.getParentId() == 0)
.map((menu) -> {
menu.setChildrenList(this.getChildren(menu,areaList));
return menu;
})
.sorted((menu1,menu2) -> {
return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null