获取菜单树状结构
菜单实体:
public class Menu implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("name")
private String name;
@TableField("parent_id")
private String parentId;
@TableField("url")
private String url;
@TableField("icon")
private String icon;
@TableField("order_num")
private String orderNum;
@TableField(exist = false)
private List<Menu> children;
}
数据结构:
获取菜单树状结构:
// 通过递归查询获取菜单树状结构
public List<Menu> getMenuTree(){
QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("parent_id","0");
List<Menu> menuList = mapper.selectList(queryWrapper);
commonMethod(menuList);
return menuList;
}
public void commonMethod(List<Menu> menuList){
for(Menu menu : menuList){
Integer id = menu.getId();
QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("parent_id",id);
List<Menu> menuList2 = mapper.selectList(queryWrapper);
menu.setChildren(menuList2);
commonMethod(menuList2);
}
}
获取菜单结果:
[
{
"id": 1,
"name": "Java",
"parentId": "0",
"url": "http://www.aliouchen.com",
"icon": "a",
"orderNum": "1",
"children": [
{
"id": 2,
"name": "并发编程",
"parentId": "1",
"url": "http://www.aliouchen.com",
"icon": "a",
"orderNum": "1",
"children": []
},
{
"id": 3,
"name": "多线程",
"parentId": "1",
"url": "http://www.aliouchen.com",
"icon": "a",
"orderNum": "2",
"children": [
{
"id": 4,
"name": "Thread",
"parentId": "3",
"url": "http://www.aliouchen.com",
"icon": "a",
"orderNum": "1",
"children": []
}
]
}
]
},
{
"id": 5,
"name": "Python",
"parentId": "0",
"url": "http://www.aliouchen.com",
"icon": "a",
"orderNum": "2",
"children": [
{
"id": 6,
"name": "Tuple",
"parentId": "5",
"url": "http://www.aliouchen.com",
"icon": "a",
"orderNum": "1",
"children": []
}
]
}
]
根据名字在树状结构做模糊查询
根据查询名字获取菜单树状结构:
// 通过查询名字使用递归方法获取菜单树状结构
//在树结构上做模糊查询(剪枝操作)
@Override
public List<Menu> getMenuByName(List<Menu> menuList,String selectName){
Iterator<Menu> iterator = menuList.iterator();
while(iterator.hasNext()){
Menu menu = iterator.next();
if(!menu.getName().contains(selectName)){
List<Menu> childrenList = menu.getChildren();
if(!CollectionUtils.isEmpty(childrenList)){
getMenuByName(childrenList, selectName);
}
if(CollectionUtils.isEmpty(childrenList)){
iterator.remove();
}
}
}
return menuList;
}
例如查询名字"多线程"结果:
[
{
"id": 1,
"name": "Java",
"parentId": "0",
"url": "http://www.aliouchen.com",
"icon": "a",
"orderNum": "1",
"children": [
{
"id": 3,
"name": "多线程",
"parentId": "1",
"url": "http://www.aliouchen.com",
"icon": "a",
"orderNum": "2",
"children": [
{
"id": 4,
"name": "Thread",
"parentId": "3",
"url": "http://www.aliouchen.com",
"icon": "a",
"orderNum": "1",
"children": []
}
]
}
]
}
]