本文最后更新于 2026年5月15日 晚上
删除角色接口的实现
删除角色接口的需求
先检查角色是否存在
要禁止删除系统内置角色(系统管理员)
检查该角色是否有用户存在 有则不允许删除
要注意的是
不应该将角色和菜单、部门的关联关系也一并删除,避免后续恢复角色时丢失权限配置
代码实现
在 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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| @Override @Transactional public ResponseResult deleteRole(Long[] ids) { if (ids == null || ids.length == 0) { return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "请选择要删除的角色"); }
List<Long> idList = List.of(ids);
List<SysRole> rolesToDelete = sysRoleService.listByIds(idList); if (rolesToDelete.size() != ids.length) { Set<Long> existIds = rolesToDelete.stream() .map(SysRole::getId) .collect(Collectors.toSet());
List<Long> notExistIds = idList.stream() .filter(id -> !existIds.contains(id)) .toList();
return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "删除失败!!原因:以下角色 id 不存在:" + notExistIds); }
List<String> protectedRoleCodes = List.of(SystemConstants.ROLE_IS_ADMIN); List<Long> protectedRoleIds = rolesToDelete.stream() .filter(role -> protectedRoleCodes.contains(role.getRoleCode()) || Objects.equals(role.getId(), 1L)) .map(SysRole::getId) .toList(); if (!protectedRoleIds.isEmpty()) { return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "删除失败!!原因:系统内置角色不允许删除:" + protectedRoleIds); }
LambdaQueryWrapper<SysUserRole> userRoleWrapper = new LambdaQueryWrapper<>(); userRoleWrapper.in(SysUserRole::getRoleId, idList) .select(SysUserRole::getRoleId); List<SysUserRole> userRoleList = sysUserRoleMapper.selectList(userRoleWrapper); if (!userRoleList.isEmpty()) { List<Long> assignedRoleIds = userRoleList.stream() .map(SysUserRole::getRoleId) .distinct() .toList(); return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "删除失败!!原因:以下角色已分配给用户,不能删除:" + assignedRoleIds); }
boolean remove = sysRoleService.removeByIds(idList); if (!remove) { return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "删除角色失败!"); }
return ResponseResult.okResult(); }
|
PS:该系列只做为作者学习开发项目做的笔记用
不一定符合读者来学习,仅供参考
预告
后续会记录博客的开发过程
每次学习会做一份笔记来进行发表
“一花一世界,一叶一菩提”
版权所有 © 2026 云梦泽
欢迎访问我的个人网站:https://hgt12.github.io/