1. 背景
一个基本的crm项目,都有获取省市区三级列表的需求,简单记录一下。
2. 代码
public List<TreeNode> findTree() {
List<AreaEntity> list = areaDao.findAll();
// 按父节点分组
ImmutableListMultimap<String, AreaEntity> multiMap = Multimaps.index(list, AreaEntity::getParentCode);
// 选取省份作为根节点
List<AreaEntity> provinces = list.stream().filter(input -> input.getType() == 1).collect(Collectors.toList());
// 递归构建省市树
return transferAndBuildTree(provinces, multiMap);
}
private List<TreeNode> transferAndBuildTree(List<AreaEntity> provinceCityEntities, ImmutableListMultimap<String, AreaEntity> multiMap) {
List<TreeNode> treeNodes = provinceCityEntities.stream().map(input -> {
TreeNode treeNode = new TreeNode();
treeNode.setValue(input.getCode());
treeNode.setLabel(input.getName());
// 子节点
ImmutableList<AreaEntity> list = multiMap.get(input.getCode());
// 没有子节点,构建完毕
if (list == null || list.isEmpty()) {
return treeNode;
}
// 递归构建子树
List<TreeNode> children = transferAndBuildTree(list, multiMap);
treeNode.setChildren(children);
return treeNode;
}).collect(Collectors.toList());
return treeNodes;
}
3. dao层表结构
CREATE TABLE `area` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`code` varchar(6) CHARACTER SET utf8 NOT NULL DEFAULT '',
`name` varchar(20) CHARACTER SET utf8 NOT NULL DEFAULT '',
`type` tinyint(20) NOT NULL DEFAULT '0',
`parent_code` varchar(6) CHARACTER SET utf8 NOT NULL DEFAULT '',
`root_code` varchar(6) CHARACTER SET utf8 DEFAULT NULL,
`deleted` tinyint(4) NOT NULL DEFAULT '0',
`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`gmt_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3248 DEFAULT CHARSET=utf8mb4;
sql数据:
因为文章篇幅有限,所以引入了一个外连接,大家自取。