展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

用户管理

  • 分页查询用户信息
# 持久层接口
public interface SysUserMapper extends BaseMapper<SysUser> {

    /**
     * 分页查询
     * @param page
     * @param sysUser
     * @return
     */
    IPage<SysUser> selectPage(Page<SysUser> page, @Param("u") SysUser sysUser);

}

# 持久层映射
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ychen.security.mapper.SysUserMapper">

    <select id="selectPage" resultType="SysUser">
        SELECT
            `id`,
            `username`,
            `password`,
            `is_account_non_expired`,
            `is_account_non_locked`,
            `is_credentials_non_expired`,
            `is_enabled`,
            `nick_name`,
            `mobile`,
            `email`,
            `create_date`,
            `update_date`
        FROM
            sys_user
        WHERE `is_enabled` = 1
        <if test="u.username != null and u.username !=''">
            AND username LIKE CONCAT('%', #{u.username}, '%')
        </if>

        <if test="u.mobile != null and u.mobile !=''">
            AND mobile = ${u.mobile}
        </if>
    </select>

</mapper>

# 业务层接口
public interface SysUserService extends IService<SysUser> {

    /**
     * 分页查询用户信息
     * @param page 分页对象
     * @param sysUser 查询条件
     * @return
     */
    IPage<SysUser> selectPage(Page<SysUser> page, SysUser sysUser);

}

# 业务层实现
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Override
    public IPage<SysUser> selectPage(Page<SysUser> page, SysUser sysUser) {
        return baseMapper.selectPage(page, sysUser);
    }

}

# 控制层接口
@Controller
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 分页查询用户列表
     * @param page 分页对象: size, current
     * @param sysUser 查询条件 : username, mobile
     * @return
     */
    @PreAuthorize("hasAuthority('sys:user:list')")
    @GetMapping("/page")
    @ResponseBody
    public MengxueguResult page(Page<SysUser> page, SysUser sysUser) {
        return MengxueguResult.ok(sysUserService.selectPage(page, sysUser));
    }

}
  • 查询用户及用户所拥有的角色
# 控制层接口
@Autowired
private SysRoleService sysRoleService;

@PreAuthorize("hasAnyAuthority('sys:user:add', 'sys:user:edit')")
@GetMapping(value={"/form", "/form/{id}"})
public String form(@PathVariable(required = false) Long id, Model model) {
    // 1, 查询用户信息,包含了用户所拥有的角色
    SysUser user = sysUserService.findById(id);
    model.addAttribute("user", user);
    // 2, 查询出所有角色信息 sys_role
    List<SysRole> roleList = sysRoleService.list();
    model.addAttribute("roleList", roleList);
    return HTML_PREFIX + "user-form";
}

# 业务层接口
/**
 * 1. 用户id查询用户信息 sys_user
 * 2. 用户id查询所拥有的角色
 * @param id
 * @return
 */
SysUser findById(Long id);

# 业务层实现
@Autowired
SysRoleMapper sysRoleMapper;

/**
 * 1. 用户id查询用户信息 sys_user
 * 2. 用户id查询所拥有的角色
 * @param id
 * @return
 */
@Override
public SysUser findById(Long id) {
    if(id == null) {
        return new SysUser();
    }
    // 1. 用户id查询用户信息 sys_user
    SysUser sysUser = baseMapper.selectById(id);
    // 2. 用户id查询所拥有的角色
    List<SysRole> roleList = sysRoleMapper.findByUserId(id);
    sysUser.setRoleList(roleList);
    return sysUser;
}

# 角色持久层接口
/**
 * 通过用户id查询所拥有的角色
 * @param userId 用户id
 * @return 查询到信息集合
 */
List<SysRole> findByUserId(@Param("userId")Long userId);

# 角色持久层映射
<select id="findByUserId" resultType="SysRole">
    SELECT
        r.*
    FROM
        sys_role r
            JOIN sys_user_role ur ON r.id = ur.role_id
            JOIN sys_user u ON ur.user_id = u.id
    WHERE
        u.id = #{userId}
</select>
  • 新增或修改用户拥有的角色
# 持久层接口
/**
 * 通过用户id删除用户角色表中的所有记录
 * @param userId
 * @return
 */
boolean deleteUserRoleByUserId(@Param("userId") Long userId);

/**
 * 保存用户角色关系表数据
 * @param userId 用户id
 * @param roleIds 角色ids
 * @return
 */
boolean saveUserRole(@Param("userId") Long userId,@Param("roleIds") List<Long> roleIds);

# 持久层映射
<!--通过用户id删除用户角色关系表数据-->
<delete id="deleteUserRoleByUserId">
    DELETE FROM sys_user_role where user_id = #{userId}
</delete>

<insert id="saveUserRole">
    INSERT INTO sys_user_role(user_id, role_id) VALUES
    <foreach collection="roleIds" item="item" index="index" separator=",">
        (#{userId}, #{item})
    </foreach>
</insert>

# 业务层实现,重写saveOrUpdate方法
@Transactional //开启事务
@Override
public boolean saveOrUpdate(SysUser entity) {
    if(entity != null && entity.getId() == null) {
        //新增设置默认密码1234
        entity.setPassword(PASSWORD_DEFAULT);
    }
    entity.setUpdateDate(new Date());
    // 1.更新或者保存操作
    boolean flag = super.saveOrUpdate(entity);
    if(flag) {
        // 2. 先删除用户角色表中的数据
        baseMapper.deleteUserRoleByUserId(entity.getId());
        // 3. 再新增到用户角色表中
        if(CollectionUtils.isNotEmpty(entity.getRoleIds())) {
            baseMapper.saveUserRole(entity.getId(), entity.getRoleIds());
        }
    }
    return true;
}

# 控制层接口
@PreAuthorize("hasAnyAuthority('sys:user:add', 'sys:user:edit')")
@RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}, value = "")
public String saveOrUpdate(SysUser sysUser) {
    // 1. 保存到用户表, 要将选择的角色保存到用户角色中间表
    sysUserService.saveOrUpdate(sysUser);
    return "redirect:/user";
}
  • 删除用户
# 业务层接口
boolean deleteById(Long id);

# 业务层实现
@Override
public boolean deleteById(Long id) {
    // 1. 查询用户信息
    SysUser sysUser = baseMapper.selectById(id);
    // 2. 再更新用户信息,将状态更新为已删除
    sysUser.setEnabled(false);
    sysUser.setUpdateDate(new Date());
    baseMapper.updateById(sysUser);
    return true;
}

# 控制层接口
@PreAuthorize("hasAuthority('sys:user:delete')")
@DeleteMapping("/{id}")
public MengxueguResult deleteById(@PathVariable Long id) {
    // 假删除,只做更新
    sysUserService.deleteById(id);
    return MengxueguResult.ok();
}
posted @ 2022-06-29 14:55  DogLeftover  阅读(15)  评论(0编辑  收藏  举报