『博客开发日记-后台』之分配角色菜单(权限)接口的实现

本文最后更新于 2026年5月14日 晚上

分配角色菜单(权限)接口的实现


分配角色菜单(权限)接口的需求

获取角色id

根据角色id查询出角色关联的菜单id,进行删除

如果前端没有传菜单id,说明就是清空该角色权限

构建新的角色菜单关系

保存新的角色菜单关系


代码实现

生成 SysRoleMenuService 和 SysRoleMenuServiceImpl


SysRoleController

1
2
3
4
5
6
7
@PutMapping("/{roleId}/menus")
@SystemLog(businessName = "分配角色菜单")
@ApiOperation(value = "分配角色菜单", notes = "给角色分配菜单(权限)", responseContainer = "List")
public ResponseResult allocationRoleMenu(@PathVariable Long roleId, @RequestBody Long[] menuIds)
{
return sysRoleService.allocationRoleMenu(roleId, menuIds);
}

SysRoleServiceImpl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@Autowired
private SysRoleMenuService sysRoleMenuService;

//分配角色菜单(权限)
@Override
public ResponseResult allocationRoleMenu(Long roleId, Long[] menuIds)
{
//获取角色id
SysRole sysRole = sysRoleService.getById(roleId);
if (sysRole == null) {
return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "该角色不存在!");
}

//根据角色id查询出角色关联的菜单id 进行删除
LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysRoleMenu::getRoleId, roleId);
sysRoleMenuService.remove(wrapper);

//如果前端没有传菜单id 说明就是清空该角色权限
if (menuIds == null || menuIds.length == 0) {
return ResponseResult.okResult();
}

//构建新的角色菜单关系
List<SysRoleMenu> roleMenuList = new ArrayList<>();
for (Long menuId : menuIds) {
SysRoleMenu roleMenu = new SysRoleMenu();
roleMenu.setRoleId(roleId);
roleMenu.setMenuId(menuId);
roleMenuList.add(roleMenu);
}

//保存新的角色菜单关系
boolean saveBatch = sysRoleMenuService.saveBatch(roleMenuList);
if (!saveBatch) {
return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "分配角色菜单失败!");
}
return ResponseResult.okResult();
}



PS:该系列只做为作者学习开发项目做的笔记用

不一定符合读者来学习,仅供参考


预告

后续会记录博客的开发过程

每次学习会做一份笔记来进行发表

“一花一世界,一叶一菩提”


版权所有 © 2026 云梦泽
欢迎访问我的个人网站:https://hgt12.github.io/


『博客开发日记-后台』之分配角色菜单(权限)接口的实现
http://example.com/2026/05/14/『博客开发日记-后台』之分配角色菜单(权限)接口的实现/
作者
云梦泽
发布于
2026年5月14日
更新于
2026年5月14日
许可协议