(B站云e办)SpringBoot开发项目实战记录(六)(管理员crud)

附加一个获取security的全局用户获取工具类

public class AdminUtils {
    public static Admin getCurrentAdmin() {
        return (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}

一、管理员crud

1.1 获取除了登录用户以外的符合条件的管理员

1. pojo层

这里的属性里面加了角色列表

/**
 * <p>
 *
 * </p>
 *
 * @author seven
 * @since 2022-01-02
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("t_admin")
@ApiModel(value="Admin对象", description="")
public class Admin implements Serializable, UserDetails {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "id")
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @ApiModelProperty(value = "姓名")
    private String name;

    @ApiModelProperty(value = "手机号码")
    private String phone;

    @ApiModelProperty(value = "住宅电话")
    private String telephone;

    @ApiModelProperty(value = "联系地址")
    private String address;

    @ApiModelProperty(value = "是否启用")
    private Boolean enabled;

    @ApiModelProperty(value = "用户名")
    private String username;

    @ApiModelProperty(value = "密码")
    private String password;

    @ApiModelProperty(value = "用户头像")
    private String userFace;

    @ApiModelProperty(value = "备注")
    private String remark;


    @ApiModelProperty(value = "角色")
    @TableField(exist = false)
    private List<Role> roles;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
        return authorities;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}

2. controller层

可条件查询的接口,不传参查所有

@Autowired
    private IAdminService adminService;

    @ApiOperation(value = "获取所有的操作员")
    @GetMapping("/")
    public List<Admin> getAllAdmins(String keywords) {
        return adminService.getAllAdmins(keywords);
    }

3. service层

传当前登录的id,在sql查询时要把个人记录去除

/**
     * 获取所有的操作员
     * @param keywords
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        // 不可以查当前已经登录的操作员id记录
        return adminMapper.getAllAdmins(AdminUtils.getCurrentAdmin().getId(), keywords);

    }

4. mapper层的xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jzq.server.mapper.AdminMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.jzq.server.pojo.Admin">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="phone" property="phone" />
        <result column="telephone" property="telephone" />
        <result column="address" property="address" />
        <result column="enabled" property="enabled" />
        <result column="username" property="username" />
        <result column="password" property="password" />
        <result column="userFace" property="userFace" />
        <result column="remark" property="remark" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, name, phone, telephone, address, enabled, username, password, userFace, remark
    </sql>

    <resultMap id="AdminWithRole" type="com.jzq.server.pojo.Admin" extends="BaseResultMap">
        <collection property="roles" ofType="com.jzq.server.pojo.Role">
            <id column="id" property="id" />
            <result column="name" property="name" />
            <result column="nameZh" property="nameZh" />
        </collection>
    </resultMap>

    <!--查询所有操作员-->
    <select id="getAllAdmins" resultMap="AdminWithRole">
        SELECT
            a.*,
            r.id rid,
            r.`name` rname,
            r.nameZh rnameZh
        FROM
            t_admin a
        LEFT JOIN
            t_admin_role ar
        ON
            a.id = ar.adminId
        LEFT JOIN
            t_role r
        ON
            r.id = ar.rid
        WHERE
            a.id != #{id}
        <if test="null != keywords and '' != keywords">
            AND a.`name` LIKE concat("%" "淑", "%")
        </if>
        ORDER BY a.id
    </select>

</mapper>

1.2 更新管理员信息

1. pojo层加个注解 @Getter(AccessLevel.NONE)

⭐知识点:因为我们的Admin继承UserDetails,所以重写了isEnabled方法,enabled属性就不需要lombok的@Data注解生成getset了,在这个属性上标注@Getter(AccessLevel.NONE)

/**
 * <p>
 *
 * </p>
 *
 * @author seven
 * @since 2022-01-02
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("t_admin")
@ApiModel(value="Admin对象", description="")
public class Admin implements Serializable, UserDetails {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "id")
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @ApiModelProperty(value = "姓名")
    private String name;

    @ApiModelProperty(value = "手机号码")
    private String phone;

    @ApiModelProperty(value = "住宅电话")
    private String telephone;

    @ApiModelProperty(value = "联系地址")
    private String address;

    @ApiModelProperty(value = "是否启用")
    @Getter(AccessLevel.NONE)
    private Boolean enabled;

    @ApiModelProperty(value = "用户名")
    private String username;

    @ApiModelProperty(value = "密码")
    private String password;

    @ApiModelProperty(value = "用户头像")
    private String userFace;

    @ApiModelProperty(value = "备注")
    private String remark;


    @ApiModelProperty(value = "角色")
    @TableField(exist = false)
    private List<Role> roles;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
        return authorities;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}

2. controller层

 @ApiOperation(value = "更新管理员信息")
    @PutMapping("/")
    public RespBean putAdmin(@RequestBody Admin admin) {
        if (adminService.updateById(admin)) {
            return RespBean.success("管理员信息更新成功");
        }
        return RespBean.warning("管理员信息更新失败");
    }

1.3 删除管理员

1. controller层

@ApiOperation(value = "删除管理员信息")
    @DeleteMapping("/{id}")
    public RespBean deleteAdmin(@PathVariable Integer id) {
        if (adminService.removeById(id)) {
            return RespBean.success("删除管理员成功");
        }
        return RespBean.warning("删除管理员失败");
    }

1.4 查询所有角色

1. controller层

	@ApiOperation(value = "获取所有的角色")
    @GetMapping("/roles")
    public List<Role> getAllRoles() {
        return roleService.list();
    }

1.5 更新管理员角色信息

1. controller层

	@ApiOperation(value = "修改管理员角色")
    @PutMapping("/role")
    public RespBean putRole(Integer adminId, Integer[] rids) {
        return adminService.updateAdminRole(adminId, rids);
    }

2. service层

⭐ 知识点:
采用删除所有角色后,再将前端传来的角色加入策略,用到事务: @Transactional
前端如果不传就是删除所有角色!

/**
     * 修改管理员权限
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    @Transactional
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
        // 删除所有的adminId的权限
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId", adminId));

        if (rids == null || rids.length == 0) {
            return RespBean.warning("用户角色全部删除成功!");
        }
        // 添加所有的传过来的权限
        Integer integer = adminRoleMapper.addAdminRole(adminId, rids);
        if (integer > 0) {
            return RespBean.success("修改管理员角色成功");
        }
        return RespBean.warning("修改管理员角色失败");
    }

3. mapper的xml

⭐ 知识:
通过<foreach > 标签实现多条记录的添加

<!--循环添加admin权限-->
    <insert id="addAdminRole">
        insert into t_admin_role(adminId, rid) values
        <foreach collection="rids" item="rid" separator=",">
            (#{adminId},#{rid})
        </foreach>
    </insert>

示例:
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值