创建数据结构
CREATE TABLE `menu` (
`id` bigint(20) unsigned NOT NULL COMMENT '主键',
`name` varchar(11) NOT NULL COMMENT '名称',
`sort_no` smallint(5) unsigned NOT NULL DEFAULT '10' COMMENT '排序号',
`parent_id` bigint(20) unsigned NOT NULL COMMENT '父节点id',
`icon` varchar(200) DEFAULT NULL COMMENT '图标',
`remark` varchar(20) DEFAULT NULL COMMENT '备注',
`url` varchar(60) DEFAULT NULL COMMENT '菜单链接',
`level` tinyint(4) DEFAULT NULL COMMENT '菜单等级',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='菜单表';
结束
组装树形结构
/**
* 递归获取下级菜单
* @param pid
* @param menus 所有菜单
* @return
*/
public List<Menu> getChild(Long pid, List<Menu> menus) {
//子菜单列表
List<Menu> childList = new ArrayList<>();
for (Menu menu : menus) {
if (pid.equals(menu.getParentId())) {
childList.add(menu);
}
}
//遍历 获取子菜单的子菜单
for (Menu menu : childList) {
List<Menu> child = getChild(menu.getId(), menus);
menu.setChildren(child);
}
//递归出口 childList长度为0
if (childList.size() == 0) {
return new ArrayList<>();
}
return childList;
}
获取所有的资源
/**
* 根据角色id获取对象集合信息
*/
public List<Menu> getAllMenus(){
List<Menu> menus = this.loadAll();
//返回的菜单树
List<Menu> rootMenus = new ArrayList<>();
for (Menu menu : menus) {
//pid(上级Id)为0的是根菜单
if (0==(menu.getParentId())) {
rootMenus.add(menu);
}
}
//遍历,找到二级菜单(根菜单的id和所有菜单中的pid比较)
for (Menu rootMenu : rootMenus) {
List<Menu> child = getChild(rootMenu.getId(), menus);
rootMenu.setChildren(child);
}
return rootMenus;
}
标签:COMMENT,菜单,menus,menu,List,如何,构建,NULL,资源
From: https://www.cnblogs.com/liuyupen/p/17405634.html