• 恒合仓库 - 角色管理、启动或禁用角色、为角色分配权限


    角色管理

    一、分页查询角色

    image-20230813213748270

    1.1 实体类

    1.1.1 分页实体类

    /**
     * 分页信息实体类:
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class Page {
    
        //当前页码
        private Integer pageNum;
    
        //每页显示行数
        private Integer pageSize;
    
        //总行数
        private Integer totalNum;
    
        //总页数
        private Integer pageCount;
    
        //limit函数参数一每页起始行
        private Integer limitIndex;
    
        //存储当前页查询到的数据的List集合
        private List<?> resultList;
    
        //计算总页数
        public Integer getPageCount() {
            return (totalNum%pageSize==0) ? totalNum/pageSize : totalNum/pageSize+1;
        }
    
        //计算limit函数参数一每页起始行
        public Integer getLimitIndex() {
            return pageSize * (pageNum-1);
        }
    
    • 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

    1.1.2 角色实体类

    /**
     * 角色表的实体类
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class Role implements Serializable {
    
        private int roleId;//角色id
    
        private String roleName;//角色名称
    
        private String roleDesc;//角色描述
    
        private String roleCode;//角色标识
    
        private String roleState;//角色状态
    
        private int createBy;//创建角色的用户id
    
        //json转换的日期格式
        @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
        private Date createTime;//创建时间
    
        private int updateBy;//修改角色的用户id
    
        private Date updateTime;//修改时间
    
        private String getCode;//追加的属性--创建角色的用户的用户名
    }
    
    • 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

    1.2 分页业务实现

    1.2.1 Mapper

    //  查询角色行数的方法
        public Integer findRoleRowCount(@Param("role") Role role);
    //  分页查询角色的方法
        public List<Role> findRolePage(@Param("page")Page page,@Param("role")Role role);
    
    • 1
    • 2
    • 3
    • 4
        
        <select id="findRoleRowCount" resultType="java.lang.Integer">
            select count(*)
            from role r
            <where>
                <if test="role.roleName !=null and role.roleName!='' ">
                     r.role_name like concat('%', #{role.roleName}, '%')
                if>
                <if test="role.roleCode !=null and role.roleCode!='' ">
                    and r.role_code like concat('%', #{role.roleCode}, '%')
                if>
                <if test="role.roleState !=null and role.roleState!='' ">
                    and r.role_state = #{role.roleState}
                if>
            where>
        select>
        
        <select id="findRolePage" resultType="com.pn.entity.Role">
            select t1.*, t2.user_code getCode
            from role t1, user_info t2
            <where>
                t1.create_by = t2.user_id
                <if test="role.roleName != null and role.roleName != ''">
                    and t1.role_name like concat('%', #{role.roleName}, '%')
                if>
                <if test="role.roleCode != null and role.roleCode != ''">
                    and t1.role_code like concat('%', #{role.roleCode}, '%')
                if>
                <if test="role.roleState != null and role.roleState != ''">
                    and t1.role_state = #{role.roleState}
                if>
                order by t1.create_time desc
                limit #{page.limitIndex}, #{page.pageSize}
            where>
        select>
    
    • 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

    1.2.2 Service

        @Override
        public Page queryRolePage(Page page, Role role) {
            Integer roleRowCount = roleMapper.findRoleRowCount(role);
    //      设置总数
            page.setTotalNum(roleRowCount);
    //      设置从哪开始
            page.setLimitIndex(page.getLimitIndex());
    //      设置总页数
            page.setPageCount(page.getPageCount());
    //      分页查询数据
            List<Role> rolePage = roleMapper.findRolePage(page, role);
            page.setResultList(rolePage);
            return page;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    1.2.3 Controller

        //分页查询角色
        @RequestMapping("/role-page-list")
        public Result roleListPage(Page page, Role role) {
            return Result.ok(roleService.queryRolePage(page,role));
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    1.2.4 效果图

    image-20230813223151165

    image-20230813225628756

    二、添加角色

    要考虑新增的角色是否存在

    根据角色名称或角色代码查询是否已有角色

    image-20230813225808309

    2.1 Mapper

    //  根据角色名称或角色代码查询角色的方法
        public Role findRoleByNameOrCode(@Param("roleName")String roleName,@Param("roleCode")String roleCode);
    
    //  添加角色的方法
        public int insertRole(@Param("role")Role role);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    <select id="findRoleByNameOrCode" resultType="com.pn.entity.Role">
        select *
        from role
        where role_name = #{roleName}
           or role_code = #{roleCode}
    select>
    <insert id="insertRole">
        insert into role
            (role_name, role_code, role_desc, role_state, create_by, create_time)
        values (#{role.roleName}, #{role.roleCode}, #{role.roleDesc}, 0, #{role.createBy}, now())
    insert>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2.2 Service

        @CacheEvict(key = "'all:role'")//记得清除一个Redis缓存中role角色信息
        @Override
        public Result saveRole(Role role) {
            Role roleByNameOrCode = roleMapper.findRoleByNameOrCode(role.getRoleName(), role.getRoleCode());
            if (roleByNameOrCode != null){
                return Result.err(Result.CODE_ERR_BUSINESS, "添加角色失败!角色已存在");
            }
            int success = roleMapper.insertRole(role);
    
            return success > 0 ? Result.ok("添加成功") : Result.err(Result.CODE_ERR_BUSINESS, "角色添加失败");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2.3 Controller

    //添加角色
    @RequestMapping("/role-add")
    public Result addRole(@RequestBody Role role, @RequestHeader("Token") String token) {
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        role.setCreateBy(currentUser.getUserId());
        
        return roleService.saveRole(role);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.4 效果图

    image-20230813235236381

    image-20230813235250175

    image-20230814000716601

    三、启用或禁用角色

    2.1 Mapper

    //  根据角色id修改角色状态的方法
        public int setRoleStateByRid(@Param("roleId")Integer roleId,@Param("roleState")String roleState);
    
    • 1
    • 2
    <update id="setRoleStateByRid">
        update role
        set role_state=#{roleState}
        where role_id = #{roleId}
    update>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.2 Service

        @CacheEvict(key = "'all:role'")//记得清除一个Redis缓存中role角色信息
        @Override
        public Result setRoleStateByRid(Role role) {
            int success = roleMapper.setRoleStateByRid(role.getRoleId(), role.getRoleState());
            return success > 0 ? Result.ok("状态修改成功") : Result.err(Result.CODE_ERR_BUSINESS, "状态修改失败");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2.3 Controller

        //启动或禁用角色的url接口
        @RequestMapping("/role-state-update")
        public Result updateRoleState(@RequestBody Role role){
            return roleService.setRoleStateByRid(role);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.4 效果图

    image-20230814153925915

    image-20230814153946449

    加入说把“出库”禁用掉后,在给用户分配角色的时候看不到“出库”角色

    image-20230814154059299

    四、删除角色

    删除时只能单个删除

    也记得删除角色用户关系表中的内容

    记得删除角色权限表中内容

    4.1 Mapper

    //  根据角色id删除角色的方法
        public int removeRoleById(@Param("roleId") Integer roleId);
    
    • 1
    • 2
    <delete id="removeRoleById">
        delete
        from role
        where role_id = #{roleId}
    delete>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    //  根据角色id删除user_role表中对应关系
        public int deleteRoleUserRelation(@Param("roleId") Integer roleId);
    
    • 1
    • 2
    <delete id="deleteRoleUserRelation">
        delete
        from user_role
        where role_id = #{roleId}
    delete>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    //根据角色id删除user_role表中对应关系
    public int deleteRoleAuthRelation(@Param("roleId") Integer roleId);
    
    • 1
    • 2
    <delete id="deleteRoleAuthRelation">
        delete
        from role_auth
        where role_id = #{roleId}
    delete>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4.2 Service

        @CacheEvict(key = "'all:role'")//记得清除一个Redis缓存中role角色信息
        @Override
        public Result deleteRoleById(Integer roleId) {
            int successRole = roleMapper.removeRoleById(roleId);
            if (successRole>0){
    //           删除用户角色关系中对应内容
                 roleMapper.deleteRoleUserRelation(roleId);
    //           删除角色权限关系
                authMapper.deleteRoleAuthRelation(roleId);
            }
            return Result.ok("删除成功");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    4.3 Controller

    //删除角色的url接口
    @RequestMapping("/role-delete/{roleId}")
    public Result deleteRole(@PathVariable("roleId") Integer roleId){
     return roleService.deleteRoleById(roleId);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4.4 效果图

    删除“采购”这个角色,id为11

    image-20230814161143302

    user_role表中没有role_id为11的

    image-20230814161338020

    role_auth表中没有role_id为11数据

    image-20230814161444932

    五、为角色分配权限

    5.1 实体类

    首先是查询所有的权限菜单树

    /auth/auth-tree 查询所有的权限菜单树

    其次是为查询某个用户权限(权限回显)

    /role/role-auth?roidId=17 根据roleId查询角色的权限

    5.1.1 权限实体类

    /**
     * auth_info表的实体类:
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Auth {
    
       private int authId;//权限(菜单)id
    
       private Integer parentId;//父权限(菜单)id
    
       private String authName;//权限(菜单)名称
    
       private String authDesc;//权限(菜单)描述
    
       private int authGrade;//权限(菜单)层级
    
       private String authType;//权限(菜单)类型
    
       private String authUrl;//权限(菜单)访问的url接口
    
       private String authCode;//权限(菜单)标识
    
       private int authOrder;//权限(菜单)的优先级
    
       private String authState;//权限(菜单)状态(1.启用,0.禁用)
    
       private int createBy;//创建权限(菜单)的用户id
    
       private Date createTime;//权限(菜单)的创建时间
    
       private int updateBy;//修改权限(菜单)的用户id
    
       private Date updateTime;//权限(菜单)的修改时间
    
       //追加的List集合属性 -- 用于存储当前权限(菜单)的子级权限(菜单)
       private List<Auth> childAuth;
    }
    
    • 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

    image-20230814215154273

    5.2 查询所有的权限菜单树

    5.2.1 Mapper

    查询所有权限菜单的方法

    //  查询所有权限菜单的方法
        public List<Auth> findAllAuth();
    
    • 1
    • 2

    auth_type的值1 模块 、2 列表、 3 按钮

        <select id="findAllAuth" resultType="com.pn.entity.Auth">
            select *
            from auth_info
            where auth_state = 1and auth_type !='3'
        select>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5.2.2 Service

    查询所有权限菜单的方法

        @Cacheable("'all:authTree'")
        @Override
        public List<Auth> allAuthTree() {
    //      查询出所有权限菜单
            List<Auth> allAuth = authMapper.findAllAuth();
    //      将所有权限菜单转成菜单树
            return allAuthToAuthTree(allAuth, 0);
        }
    
        //  将所有菜单List转成菜单树List
    //  第一次的话pid是0
        private  List<Auth> allAuthToAuthTree( List<Auth> allAuthList,Integer pid){
            List<Auth> firstLevelAuthList = new ArrayList<>();
    
    //      查询出所有n级菜单(比如说一级菜单)
            for (Auth auth:allAuthList){
    //          pid=0,说明就是1级菜单
               if ( auth.getParentId().equals(pid)){
                   firstLevelAuthList.add(auth);
               }
            }
    //      拿到每一个n级菜单的(n+1)级菜单
            for (Auth firstAuth: firstLevelAuthList){
    //          递归,获取(n+1)级菜单
                List<Auth> secondLevelAuthList = allAuthToAuthTree(allAuthList,firstAuth.getAuthId());
                firstAuth.setChildAuth(secondLevelAuthList);
            }
    
            return firstLevelAuthList;
        }
    
    • 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

    5.2.3 Controller

    查询所有权限菜单的方法

    @Slf4j
    @RestController
    @RequestMapping("/auth")
    public class AuthController {
        @Autowired
        private AuthService authService;
    
        @RequestMapping("/auth-tree")
        public Result loadAllAuthTree(){
            return Result.ok(authService.allAuthTree());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    5.2.4 效果图

    image-20230814222132934

    5.3 当前角色的权限回显

    /role/role-auth?roidId=17 根据roleId查询角色已分配的所有权限id

    5.3.1 Mapper

    //  根据角色id查询分配的所有权限菜单的方法
        public List<Integer> findAuthIdByRid(@Param("roleId") Integer roleId);
    
    • 1
    • 2
        <select id="findAuthIdByRid" resultType="java.lang.Integer">
                    select auth_info.auth_id
                    from role_auth,
                         auth_info
                    where role_auth.auth_id = auth_info.auth_id
                      and role_auth.role_id = #{roleId}
                      and auth_info.auth_state=1
                      and auth_info.auth_type != 3
        select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    5.3.2 Service

        @Override
        public List<Integer> findAuthByRid(Integer roleId) {
            return authMapper.findAuthIdByRid(roleId);
        }
    
    • 1
    • 2
    • 3
    • 4

    5.3.3 Controller

        @Autowired
        private AuthService authService;
    
        @RequestMapping("/role-auth")
        public Result roleAuth(Integer roleId){
            return  Result.ok( authService.findAuthByRid(roleId));
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    5.3.4 效果图

    image-20230814225732526

    5.4 为角色分配权限

    5.4.1 实体类

    /**
     * 接收给角色分配权限(菜单)前端传递的数据的Dto类:
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class AssignAuthDto {
    
        //接收请求参数roleId -- 角色id
        private Integer roleId;
    
        //接收请求参数authIds -- 给角色分配的所有权限(菜单)的id
        private List<Integer> authIds;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    5.4.2 Mapper

    //根据角色id删除user_role表中对应关系
    public int deleteRoleAuthRelation(@Param("roleId") Integer roleId);
    
    • 1
    • 2
    <delete id="deleteRoleAuthRelation">
        delete
        from role_auth
        where role_id = #{roleId}
    delete>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    //  添加角色权限关系的方法
        public int insertRoleAuth(@Param("roleId") Integer roleId,@Param("authId") Integer authId);
    
    • 1
    • 2
    <insert id="insertRoleAuth">
        insert into role_auth
         values (null ,#{roleId},#{authId})
    insert>
    
    • 1
    • 2
    • 3
    • 4

    5.4.3 Service

        @Transactional
        @Override
        public void saveRoleAuth(AssignAuthDto assignAuthDto) {
    //       删除角色与权限之前的对应关系
            authMapper.deleteRoleAuthRelation(assignAuthDto.getRoleId());
    //      添加角色权限关系
            List<Integer> authIds = assignAuthDto.getAuthIds();
            for (Integer authId : authIds){
                authMapper.insertRoleAuth(assignAuthDto.getRoleId(),authId);
            }
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    5.4.4 Controller

    @RequestMapping("/auth-grant")
    public Result grantAuth(@RequestBody AssignAuthDto assignAuthDto){
           roleService.saveRoleAuth(assignAuthDto);
           return Result.ok("权限分配成功");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5.4.5 效果图

    image-20230814233035355

  • 相关阅读:
    【附源码】计算机毕业设计java原创网络文学管理系统设计与实现
    Opencv项目实战:02 角度探测器
    21.7 Python 使用Request库
    初识数据结构——时间复杂度
    如何通过企业数字化管理降本增效?
    Vue+el-image-viewer显示tiff图片,并能够切换图片中的帧
    OJ练习第180题——颠倒二进制位
    项目实战:通过axios加载水果库存系统的首页数据
    LeetCode_位运算_中等_260.只出现一次的数字 III
    在docker上安装AWVS
  • 原文地址:https://blog.csdn.net/weixin_51351637/article/details/133036016