• 恒合仓库 - 用户管理、用户列表、为用户分配角色


    用户管理

    一、用户列表

    分页查询用户

    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
    • 37

    1.1.2 用户信息实体类

    /**
     * user_info表的实体类:
     */
    @Data
    @ToString
    public class User {
    
       private int userId;//用户id
    
       private String userCode;//账号
    
       private String userName;//用户名
    
       private String userPwd;//用户密码
    
       private String userType;//用户类型
    
       private String userState;//用户状态
    
       private String isDelete;//删除状态
    
       private int createBy;//创建人
    
       //返回前端时,自动将Date转换成指定格式的json字符串
       @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
       private Date createTime;//创建时间
    
       private int updateBy;//修改人
    
       private Date updateTime;//修改时间
    
       private String getCode; //追加的属性,数据库没有:用户创建人
    
       public User() {
    
       }
    
       public User(int userId, String userCode, String userName, String userPwd,
             String userType, String userState, String isDelete, int createBy,
             Date createTime, int updateBy, Date updateTime) {
          this.userId = userId;
          this.userCode = userCode;
          this.userName = userName;
          this.userPwd = userPwd;
          this.userType = userType;
          this.userState = userState;
          this.isDelete = isDelete;
          this.createBy = createBy;
          this.createTime = createTime;
          this.updateBy = updateBy;
          this.updateTime = updateTime;
       }
    }
    
    • 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

    1.2 业务实现

    1.2.1 UserMapper

    Mybatis - 基础_我爱布朗熊的博客-CSDN博客

    //  查询用户总行数的方法
        public Integer findRowCount(User user);
    
    //  分页查询用户的方法。
    //  为参数对象起别名是为了在拼接SQL时好区分
        public List<User> findUserByPage(@Param("page") Page page,@Param("user") User user);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    编写SQL

     
        <select id="findRowCount" resultType="java.lang.Integer">
            select count(*)
            from user_info
            <where>
                is_delete=0
                <if test="userCode !=null and userCode!=''">
                    and user_code like concat('%', #{userCode}, '%')
                if>
                <if test="userType!=null and userType!='' ">
                    and user_type = #{userType}
                if>
                <if test="userState !=null and userState!='' ">
                    and user_state = #{userState}
                if>
            where>
        select>
    
        
        <select id="findUserByPage" resultType="com.pn.entity.User">
            select t1.*,t2.user_code as getCode
            from user_info t1,user_info t2
            <where>
                t1.create_by = t2.user_id
                and t1.is_delete =0
                <if test="user.userCode !=null and user.userCode!=''">
                    and t1.user_code like  concat('%', #{user.userCode}, '%')
                if>
                <if test="user.userType!=null and user.userType!='' ">
                    and t1.user_type = #{user.userType}
                if>
                <if test="user.userState !=null and user.userState!='' ">
                    and t1.user_state = #{user.userState}
                if>
            where>
            order by t1.create_time desc
            limit #{page.limitIndex}, #{page.pageSize}
        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
    • 36
    • 37
    • 38

    1.2.2 Service层

        //分页查询的用户方法
        @Override
        public Page queryUserByPage(Page page, User user) {
            Integer rowCount = userMapper.findRowCount(user);
    //      设定数据总行数
            page.setTotalNum(rowCount);
    //      设定一共多少页
            page.setPageCount(page.getPageCount());
    //      设定每一页的起始行
            page.setLimitIndex(page.getLimitIndex());
    
            List<User> userByPage = userMapper.findUserByPage(page, user);
    
            page.setResultList(userByPage);
    
            return page;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    1.2.3 Controller层

    //  分页查询用户url接口,接收的参数不是JSON类型
    //  Page接收参数pageNum、pageSize ;
    //  User接收参数 userCode、userType、userState
        @RequestMapping("/user-list")
        public Result getUserList(Page page, User user){
           return Result.ok(userService.queryUserByPage(page,user));
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    1.2.4 效果图

    image-20230811225518688

    二、用户增删改查

    2.1 添加用户业务实现

    一个表单而已

    image-20230811230908577

    2.1.1 Mapper

    //  添加用户
        public int addUser(User user);
    
    • 1
    • 2

    主键虽然自增,我们也用null占位

    
    <insert id="addUser">
        insert into user_info
            value (#{userCode},#{userName},#{userPwd},null,0,0,#{createBy},now(),null,null)
    insert>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    //  根据账号查询用户信息的方法啊
        public User findUserByCode(String userCode);
    
    • 1
    • 2
    
    <select id="findUserByCode" resultType="com.pn.entity.User">
        select *
        from user_info
        where user_code = #{userCode}
          and is_delete = '0'
    select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2.1.2 Service

        //添加用户的业务
        @Override
        public Result saveUser(User user) {
    //      对密码加密
            String password = DigestUtil.hmacSign(user.getUserPwd());
            user.setUserPwd(password);
            int success = userMapper.addUser(user);
            
            return success>0? Result.ok("添加成功") : Result.err(Result.CODE_ERR_BUSINESS,"添加用户失败");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2.1.3 Controller

    //  利用token获取是谁添加的用户
        @RequestMapping("/addUser")
        public Result addUser(@RequestBody User user, @RequestHeader("Token") String token){
            CurrentUser currentUser = tokenUtils.getCurrentUser(token);
            user.setCreateBy(currentUser.getUserId());
            return userService.saveUser(user);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2.1.4 效果图

    image-20230811234153942

    2.2 删除用户业务实现

    删除的时候可以批量删除,也可以单个删除

    删除用户的时候记得删除用户对应的角色关系表中的内容(不删除也行,等恢复账户的时候也能恢复之前的角色信息)

    2.2.1 Mapper

    //  根据用户ids修改用户为删除状态的方法
        public int setIsDeleteByUids(List<Integer> userIdList);
    
    • 1
    • 2

    Mybatis参数的都是被一个Map集合封装的

    如果参数是List集合的话,那默认的键就是纯小写的“list”(如果指定名称的话例外)

    
    
    <update id="setIsDeleteByUids">
        update user_info set is_delete=1 where user_id in
    
        <foreach collection="list" item="id" separator="," open="(" close=")">
            #{id}
        foreach>
    
    update>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2.2.2 Service

    //  批量删除用户
        @Override
        public Result deleteUserByIds(List<Integer> userIdList) {
            int success = userMapper.setIsDeleteByUids(userIdList);
            return success>0? Result.ok("删除用户成功") : Result.err(Result.CODE_ERR_BUSINESS,"删除用户失败");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2.2.3 Controller

    //根据用户id删除单个用户的URL接口
    @RequestMapping("/deleteUser/{userId}")
    public Result deleteUserById(@PathVariable Integer userId) {
        return userService.deleteUserByIds(Collections.singletonList(userId));
    }
    
    //根据用户ids批量删除用户的url接口
    @RequestMapping("/deleteUserList")
    public Result deleteUserById(@RequestBody List<Integer> userIdList) {
        return userService.deleteUserByIds(userIdList);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2.2.4 效果图

    image-20230813195942442

    2.3 修改用户业务实现

    只能修改昵称

    image-20230813200810531

    2.3.1 Mapper

    //  修改用户昵称的方法
        public int setUserNameByUid(@Param("userId")Integer userId,@Param("userName")String userName, @Param("updateBy")int updateBy );
    
    • 1
    • 2
    
    <update id="setUserNameByUid">
        update user_info
        set user_name=#{userName},
            update_by=#{updateBy},
            update_time=now()
        where user_id = #{userId}
    update>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.3.2 Service

    //  修改用户昵称
        @Override
        public Result setUserById(Integer userId, String userName, int updateBy) {
            int success = userMapper.setUserNameByUid(userId, userName, updateBy);
    
            return success>0? Result.ok("删除用户成功") : Result.err(Result.CODE_ERR_BUSINESS,"删除用户失败");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2.3.3 Controller

    //修改用户昵称
    @RequestMapping("/updateUser")
    public Result updateUser(@RequestBody User user, @RequestHeader("Token") String token){
        return userService.setUserById(user.getUserId(), user.getUserName(),, tokenUtils.getCurrentUser(token).getUserId());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.3.4 效果图

    image-20230813202544282

    改完名称后

    image-20230813202614407

    2.4 修改密码

    将用户的密码重置为123456

    2.4.1 Mapper

    //  根据用户id修改密码的方法
        public int setPwdByUid(@Param("userId")Integer userId,@Param("password")String password);
    
    • 1
    • 2
    <update id="setPwdByUid">
        update user_info
        set user_pwd = #{password}
        where user_id = #{userId}
    update>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.4.2 Service

        @Override
        public Result setPwdByUid(Integer userId) {
            String password = DigestUtil.hmacSign("123456");
            int success = userMapper.setPwdByUid(userId, password);
    
            return success>0? Result.ok("重置密码成功") : Result.err(Result.CODE_ERR_BUSINESS,"重置密码失败");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2.4.3 Controller

        //根据用户id初始化用户密码
        @RequestMapping("/updatePwd/{userId}")
        public Result resetPassword(@PathVariable("userId") Integer userId){
            return userService.setPwdByUid(userId);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.4.5 效果图

    image-20230813204327239

    三、启动或禁用用户

    3.1 业务实现

    3.1.1 Mapper

    //  根据用户id修改用户的状态
        public int updateStateByUid(@Param("userId") int userId,@Param("userState") String userState);
    
    • 1
    • 2
    <!--根据用户id修改用户状态-->
    <update id="updateStateByUid">
        update user_info
        set user_state = #{userState}
        where user_id = #{userId}
    </update>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3.1.2 Service

    //启动或禁用用户
    @Override
    public Result setUserState(User user) {
        int success = userMapper.updateStateByUid(user.getUserId(), user.getUserState());
    
        return success>0? Result.ok("修改成功"):Result.err(Result.CODE_ERR_BUSINESS,"修改失败");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3.1.3 Controller

    //  启动或禁用用户
        @RequestMapping("/updateState")
        public Result updateState(@RequestBody User user){
            return  userService.setUserState(user);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3.1.4 效果图

    将下面的用户进行禁用

    image-20230812183423806

    禁用后如下图所示

    image-20230812183447909

    四、为用户分配角色

    也就是下面红框中的内容

    image-20230812184122455

    image-20230812184139912

    4.1 实体类

    4.1.1 角色表实体类

    /**
     * 角色表的实体类
     */
    @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

    4.2 获取所有角色

    Springboot操作Redis注解形式缓存

    4.2.1 开启Redis注解版缓存

    ①在启动类上添加@EnableCaching开启Redis注解版缓存

    //mapper接口扫描器,然后会自动为Mapper接口创建代理对象并加入到IOC容器
    @MapperScan(basePackages = "com.pn.mapper")
    @SpringBootApplication
    @EnableCaching//开启Redis注解版缓存
    public class WarehouseApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(WarehouseApplication.class, args);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    ②在我们所需的类上添加@CacheConfig注解指定缓存的名称(数据保存到redis中的键的前缀)

    //指定缓存的名称(数据保存到redis中的键的前缀)
    @CacheConfig(cacheNames = "com.pn.service.impl.RoleServiceImpl")
    @Service
    public class RoleServiceImpl implements RoleService {
    .....
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    ③在我们所需要的方法上标注注解@Cacheable指定缓存的键

    @Cacheable(key = "'all:role'")
    @Override
    public List<Role> getAllRole() {
        return roleMapper.getAllRole();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4.2.2 Mapper

    @Mapper
    public interface RoleMapper {
    //  查询所有角色的方法
        public List<Role> getAllRole();
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    <select id="getAllRole" resultType="com.pn.entity.Role">
        select *
        from role
        where role_state = 1
    </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4.2.3 Service

    //指定缓存的名称(数据保存到redis中的键的前缀)
    @CacheConfig(cacheNames = "com.pn.service.impl.RoleServiceImpl")
    @Service
    public class RoleServiceImpl implements RoleService {
        @Autowired
        private RoleMapper roleMapper;
    
    
        @Cacheable(key = "'all:role'")
        @Override
        public List<Role> getAllRole() {
            return roleMapper.getAllRole();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    4.2.4 Controller

    @RestController
    @RequestMapping("/role")
    public class RoleController {
        //注入RoleService
        @Autowired
        private RoleService roleService;
    
        //查询所有角色
        @RequestMapping("/role-list")
        public Result roleList() {
            return Result.ok(roleService.getAllRole());
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    4.2.5 效果图

    image-20230812230932457

    image-20230812231029485

    4.3 角色回显效果

    我们某个用户已经有角色了,但是他并没有打上"√"

    下面就来实现一下角色回显

    image-20230812230932457

    4.3.1 Mapper

    //  根据userId查询对应角色
        public  List<Role> getRoleByUserId(@Param("userId") Integer userId);
    
    • 1
    • 2
        <select id="getRoleByUserId" resultType="com.pn.entity.Role">
            select r.*
            from user_role u1,
                 role r
            where u1.user_id = #{userId}
              and u1.role_id = r.role_id
              and r.role_state= 1
        select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    4.3.2 Service

    @Override
    public List<Role> getRoleByUserId(Integer userId) {
        return roleMapper.getRoleByUserId(userId);
    }
    
    • 1
    • 2
    • 3
    • 4

    4.3.3 Controller

        @Autowired
        private RoleService roleService;
        
    //  获取用户已经分配的角色
        @RequestMapping("/user-role-list/{userId}")
        public Result userRoleList(@PathVariable("userId") Integer userId){
              return Result.ok(roleService.getRoleByUserId(userId));
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    4.3.4 效果图

    image-20230812232701472

    4.4 分配角色

    处理的逻辑也很简单,把之前分配的角色删除,然后重新分配,这样就不用判断用户是否有某个角色了

    4.4.1 Dto类

    /**
     * 接收给用户分配角色前端传递的数据的Dto类:
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class AssignRoleDto {
    
        //接收请求参数userId -- 用户id
        private Integer userId;
    
        //接收请求参数roleCheckList -- 给用户分配的所有角色名
        private List<String> roleCheckList;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    4.4.2 Mapper

    ①根据角色名查询角色id

    //  根据角色名查询角色id
        public Integer findRoleIdByName(String roleName);
    
    • 1
    • 2
    
    <select id="findRoleIdByName" resultType="java.lang.Integer">
        select role.role_id
        from role
        where role.role_name = #{roleName}
    select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    ②删除已经用户分配的角色

    删除关系表的信息即可

    //  根据用户Id删除用户已经分配的角色关系
        public int removeUserRoleByUid(Integer userId);
    
    • 1
    • 2
    
    <delete id="removeUserRoleByUid">
        delete
        from user_role
        where user_id = #{userId}
    delete>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    ③向user_role表添加用户角色对应关系

    //  向user_role表添加用户角色对应关系
        public int insertUserRole(@Param("userId") Integer userId,@Param("roleId")Integer roleId);
    
    • 1
    • 2
    <insert id="insertUserRole">
        insert into user_role values(null,#{roleId},#{userId})
    insert>
    
    • 1
    • 2
    • 3

    4.4.3 Service

        //  给用户修改角色信息
        @Override
        public Result changeUserRole(AssignRoleDto assignRoleDto) {
    //      将之前的关系删除掉
            roleMapper.removeUserRoleByUid(assignRoleDto.getUserId());
    
    //      获取我们要添加的角色的ID
            List<String> roleNameList = assignRoleDto.getRoleCheckList();
            for(String role:roleNameList){
                Integer roleId = roleMapper.findRoleIdByName(role);
                roleMapper.insertUserRole(assignRoleDto.getUserId(),roleId);
            }
    
            return Result.ok("更改角色成功");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    4.4.4 Controller

    //  给用户分配角色
        @RequestMapping("/assignRole")
        public Result assignRole(@RequestBody AssignRoleDto assignRoleDto){
            return userService.changeUserRole(assignRoleDto);;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4.4.5 效果图

    image-20230813000523491

  • 相关阅读:
    云计算就业方向及前景怎么样
    【PTHREAD】线程互斥与同步之条件变量
    kubeadm快速部署K8S
    电视连续剧 ffmpeg 批量去掉片头片尾
    Vue3 toRaw 和 markRaw
    2021年03月 Python(四级)真题解析#中国电子学会#全国青少年软件编程等级考试
    UE4 第一人称角色模板 添加冲刺(加速)功能
    【Verycapture】离线文字提取,视频录制
    欧拉系统(euleros):升级Mysql
    使用 Certbot 为 Nginx 自动配置 SSL 证书
  • 原文地址:https://blog.csdn.net/weixin_51351637/article/details/133035798