CREATE TABLE `tree_data` (
`id` int(11) DEFAULT NULL,
`code` varchar(64) DEFAULT NULL,
`name` varchar(64) DEFAULT NULL,
`parent_code` varchar(64) DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
转化使用
public List<TreeNode> getTree() {
List<TreeNode> tree = publicMapper.getTree();
Map<String, TreeNode> treeMap = new HashMap<>();
// 构建节点映射
for (TreeNode treeNode : tree) {
treeNode.setChildren(new ArrayList<>()); // 初始化子节点列表
treeMap.put(treeNode.getCode(), treeNode);
}
List<TreeNode> result = new ArrayList<>();
for (TreeNode treeNode : tree) {
String pcode = treeNode.getPcode();
// 判断根节点的条件
if ("14".equals(pcode)) {
// 根节点
result.add(treeNode);
} else {
// 非根节点,将当前节点加入到父节点的子节点列表中
TreeNode parent = treeMap.get(pcode);
if (parent != null) {
parent.getChildren().add(treeNode);
}
}
}
return result;
}
publicMapper.getTree()
<select id="getTree" resultType="com.sxwy.mybatisplus.practice.TreeNode">
select id,code,name,parent_code
from sys_danwei_ml where code != '14' order by code desc ;
</select>
TreeNode
import java.util.List;
@Data
public class TreeNode {
private String id;
private String code;
private String name;
private String parentCode;
private List<TreeNode> children;
}