在写项目的权限管理模块、用户系统的时候经常碰见类似的树结构我们一般习惯称之为权限树,权限树应用的地方有很多,比较常见的有:权限管理时候的树状图,页面左侧的一二三级的菜单,物品分类的树状菜单。
在实际项目中这种权限结构,数据库设计一般是这样的:
CREATE TABLE `bh_module` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '模块id',
`parent_id` int(12) NULL DEFAULT NULL COMMENT '父节点id',
`parent_name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '父节点名称',
`name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '模块名称',
`module_code` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '模块业务码',
`remark` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '模块说明',
`created_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`creator` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建者',
`updated_at` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
`modifier` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '修改者',
`delete_flag` int(2) NULL DEFAULT 0 COMMENT '删除标识 0为不删 1为删除',
PRIMARY KEY (`id`) USING BTREE
) ;
java代码如下:
public class MenuTreeUtil {
private List<BhModule> nodes;
private List<BhRoleModule> checknodes;
/**
* 创建一个新的实例 Tree.
*
* @param nodes 将树的所有节点都初始化进来。
*/
public MenuTreeUtil(List<BhModule> nodes, List<BhRoleModule> checknodes) {
this.nodes = nodes;
this.checknodes = checknodes;
}
/**
* buildTree
* 描述: 创建树
*
* @return List<Map < String , Object>>
* @throws
* @since 1.0.0
*/
public List<BhModule> buildTreeGrid() {
List<BhModule> list = new ArrayList<BhModule>();
for (BhModule node : nodes) {
//这里判断父节点,需要自己更改判断
if (node.getParentId().equals(0L)) {
List<BhModule> childs = buildTreeGridChilds(node);
node.setChildren(childs);
list.add(node);
}
}
return list;
}
/**
* buildChilds
* 描述: 创建树下的节点。
*
* @param node
* @return List<Map < String , Object>>
* @throws
* @since 1.0.0
*/
private List<BhModule> buildTreeGridChilds(BhModule node) {
List<BhModule> list = new ArrayList<BhModule>();
List<BhModule> childNodes = getChilds(node);
for (BhModule childNode : childNodes) {
//System.out.println("childNode"+childNode.getMenuName());
List<BhModule> childs = buildTreeGridChilds(childNode);
childNode.setChildren(childs);
list.add(childNode);
}
return list;
}
/**
* getChilds
* 描述: 获取子节点
*
* @param parentNode
* @return List<Resource>
* @throws
* @since 1.0.0
*/
public List<BhModule> getChilds(BhModule parentNode) {
List<BhModule> childNodes = new ArrayList<BhModule>();
for (BhModule node : nodes) {
//System.out.println(node.getParentId()+"-------"+parentNode.getId());
//子节点和父节点作对比
if (node.getParentId().equals(parentNode.getId())) {
childNodes.add(node);
}
}
return childNodes;
}
}
handler中调用这个工具类:
MenuTreeUtil menuTreeUtil = new MenuTreeUtil(moduleList, null);
List<BhModule> treeGridList = menuTreeUtil.buildTreeGrid();
即可返回树列表,剩下的事就是前端解析了。