一、前言
最近在寫一個博客的項目卓箫,菜單頁面需要遞歸實現(xiàn)载矿。
天天寫crud遞歸都忘了咋寫。一邊百度一邊好不容易寫完了烹卒。
在此記錄一下闷盔。
表結(jié)構(gòu):
create table sys_menu
(
menu_id bigint auto_increment comment '菜單ID'
primary key,
menu_name varchar(50) not null comment '菜單名稱',
parent_id bigint default 0 null comment '父菜單ID',
order_num int(4) default 0 null comment '顯示順序',
url varchar(200) default '#' null comment '請求地址',
target varchar(20) default '' null comment '打開方式(menuItem頁簽 menuBlank新窗口)',
menu_type char default '' null comment '菜單類型(M目錄 C菜單 F按鈕)',
visible char default '0' null comment '菜單狀態(tài)(0顯示 1隱藏)',
perms varchar(100) null comment '權(quán)限標(biāo)識',
icon varchar(100) default '#' null comment '菜單圖標(biāo)',
is_deleted varchar(1) default '0' null comment '刪除狀態(tài)(0顯示 1刪除)',
create_by varchar(64) default '' null comment '創(chuàng)建者',
create_time datetime null comment '創(chuàng)建時間',
update_by varchar(64) default '' null comment '更新者',
update_time datetime null comment '更新時間',
remark varchar(500) default '' null comment '備注'
)
comment '菜單權(quán)限表';
二、 實現(xiàn)思路
- 遍歷所有菜單旅急,把parentId字段為0添加到父集合中逢勾。
- 遍歷父菜單集合,調(diào)用方法getChildList(allList, menuId)藐吮。
- getChildList(allList, menuId) 遍歷所有parentId等于menuId添加到子集合中溺拱。遍歷子集合調(diào)用getChildList(allList, menuId) 方法。
三谣辞、 具體代碼
public List<SysMenu> selectMenusByUser(SysUser user) {
List<SysMenu> menuList = menuMapper.selectMenusByUserId(user.getUserId());
return getChildPerms(menuList);
}
private List<SysMenu> getChildPerms(List<SysMenu> allMenuList) {
List<SysMenu> rootList = new ArrayList<>();
for (Iterator<SysMenu> lt = allMenuList.iterator(); lt.hasNext(); ) {
SysMenu menu = lt.next();
if (menu.getParentId() == 0) {
rootList.add(menu);
lt.remove();
}
}
for (SysMenu menu : rootList) {
menu.setChildren(getChild(allMenuList, menu.getMenuId()));
}
return rootList;
}
private List<SysMenu> getChild(List<SysMenu> allMenuList, Long id) {
List<SysMenu> childList = new ArrayList<>();
for (Iterator<SysMenu> lt = allMenuList.iterator(); lt.hasNext(); ) {
SysMenu menu = lt.next();
if (menu.getParentId().equals(id)) {
childList.add(menu);
lt.remove();
}
}
for (SysMenu menu : childList) {
menu.setChildren(getChild(allMenuList, menu.getMenuId()));
}
return childList;
}
四迫摔、 總結(jié)
代碼一看就會,用的時候就是想不起來泥从。
代碼很簡單句占,最基本的遞歸。