角色关联权限操作
<a href="${pageContext.request.contextPath}/role/findRoleByIdAndAllPermission.do?id=${role.id}" class="btn bg-olive btn-xs">添加权限</a>
RoleController
//根据roleId查询role,并查询出可以添加的权限 @RequestMapping("/findRoleByIdAndAllPermission.do") public ModelAndView findRoleByIdAndAllPermission(@RequestParam(name = "id", required = true) String roleId) throws Exception { ModelAndView mv = new ModelAndView(); //根据roleId查询role Role role = roleService.findById(roleId); //根据roleId查询可以添加的权限 List<Permission> otherPermissions = roleService.findOtherPermissions(roleId); mv.addObject("role", role); mv.addObject("permissionList", otherPermissions); mv.setViewName("role-permission-add"); return mv; }
RoleServiceImpl
@Override public Role findById(String roleId) throws Exception { return roleDao.findById(roleId); } @Override public List<Permission> findOtherPermissions(String roleId) { return roleDao.findOtherPermissions(roleId); }
IRoleDao
@Select("select * from role where id=#{roleId}") @Results({ @Result(id = true,property = "id",column = "id"), @Result(property = "roleName",column = "roleName"), @Result(property = "roleDesc",column = "roleDesc"), @Result(property = "permissions",column = "id",javaType = java.util.List.class,many = @Many(select = "com.itheima.ssm.dao.IPermissionDao.findPermissionByRoleId")) }) Role findById(String roleId); @Select("select * from permission where id not in (select permissionId from role_permission where roleId=#{roleId})") List<Permission> findOtherPermissions(String roleId);
添加权限
RoleController
//给角色添加权限 @RequestMapping("/addPermissionToRole.do") public String addPermissionToRole(@RequestParam(name = "roleId", required = true) String roleId, @RequestParam(name = "ids", required = true) String[] permissionIds) throws Exception { roleService.addPermissionToRole(roleId, permissionIds); return "redirect:findAll.do"; }
RoleServiceImpl
@Override public void addPermissionToRole(String roleId, String[] permissionIds) { for(String permissionId:permissionIds){ roleDao.addPermissionToRole(roleId,permissionId); } }
IRoleDao
@Insert("insert into role_permission(roleId,permissionId) values(#{roleId},#{permissionId})") void addPermissionToRole(@Param("roleId") String roleId, @Param("permissionId") String permissionId); }