分页查询用户
/**
* 分页信息实体类:
*/
@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);
}
}
/**
* 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;
}
}
Mybatis - 基础_我爱布朗熊的博客-CSDN博客
// 查询用户总行数的方法
public Integer findRowCount(User user);
// 分页查询用户的方法。
// 为参数对象起别名是为了在拼接SQL时好区分
public List<User> findUserByPage(@Param("page") Page page,@Param("user") User user);
编写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>
//分页查询的用户方法
@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;
}
// 分页查询用户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));
}
一个表单而已
// 添加用户
public int addUser(User user);
主键虽然自增,我们也用null占位
<insert id="addUser">
insert into user_info
value (#{userCode},#{userName},#{userPwd},null,0,0,#{createBy},now(),null,null)
insert>
// 根据账号查询用户信息的方法啊
public User findUserByCode(String userCode);
<select id="findUserByCode" resultType="com.pn.entity.User">
select *
from user_info
where user_code = #{userCode}
and is_delete = '0'
select>
//添加用户的业务
@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,"添加用户失败");
}
// 利用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);
}
删除的时候可以批量删除,也可以单个删除
删除用户的时候记得删除用户对应的角色关系表中的内容(不删除也行,等恢复账户的时候也能恢复之前的角色信息)
// 根据用户ids修改用户为删除状态的方法
public int setIsDeleteByUids(List<Integer> userIdList);
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>
// 批量删除用户
@Override
public Result deleteUserByIds(List<Integer> userIdList) {
int success = userMapper.setIsDeleteByUids(userIdList);
return success>0? Result.ok("删除用户成功") : Result.err(Result.CODE_ERR_BUSINESS,"删除用户失败");
}
//根据用户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);
}
只能修改昵称
// 修改用户昵称的方法
public int setUserNameByUid(@Param("userId")Integer userId,@Param("userName")String userName, @Param("updateBy")int updateBy );
<update id="setUserNameByUid">
update user_info
set user_name=#{userName},
update_by=#{updateBy},
update_time=now()
where user_id = #{userId}
update>
// 修改用户昵称
@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,"删除用户失败");
}
//修改用户昵称
@RequestMapping("/updateUser")
public Result updateUser(@RequestBody User user, @RequestHeader("Token") String token){
return userService.setUserById(user.getUserId(), user.getUserName(),, tokenUtils.getCurrentUser(token).getUserId());
}
改完名称后
将用户的密码重置为123456
// 根据用户id修改密码的方法
public int setPwdByUid(@Param("userId")Integer userId,@Param("password")String password);
<update id="setPwdByUid">
update user_info
set user_pwd = #{password}
where user_id = #{userId}
update>
@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,"重置密码失败");
}
//根据用户id初始化用户密码
@RequestMapping("/updatePwd/{userId}")
public Result resetPassword(@PathVariable("userId") Integer userId){
return userService.setPwdByUid(userId);
}
// 根据用户id修改用户的状态
public int updateStateByUid(@Param("userId") int userId,@Param("userState") String userState);
<!--根据用户id修改用户状态-->
<update id="updateStateByUid">
update user_info
set user_state = #{userState}
where user_id = #{userId}
</update>
//启动或禁用用户
@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,"修改失败");
}
// 启动或禁用用户
@RequestMapping("/updateState")
public Result updateState(@RequestBody User user){
return userService.setUserState(user);
}
将下面的用户进行禁用
禁用后如下图所示
也就是下面红框中的内容
/**
* 角色表的实体类
*/
@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;//追加的属性--创建角色的用户的用户名
}
Springboot操作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);
}
}
②在我们所需的类上添加@CacheConfig注解指定缓存的名称(数据保存到redis中的键的前缀)
//指定缓存的名称(数据保存到redis中的键的前缀)
@CacheConfig(cacheNames = "com.pn.service.impl.RoleServiceImpl")
@Service
public class RoleServiceImpl implements RoleService {
.....
}
③在我们所需要的方法上标注注解@Cacheable指定缓存的键
@Cacheable(key = "'all:role'")
@Override
public List<Role> getAllRole() {
return roleMapper.getAllRole();
}
@Mapper
public interface RoleMapper {
// 查询所有角色的方法
public List<Role> getAllRole();
}
<select id="getAllRole" resultType="com.pn.entity.Role">
select *
from role
where role_state = 1
</select>
//指定缓存的名称(数据保存到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();
}
}
@RestController
@RequestMapping("/role")
public class RoleController {
//注入RoleService
@Autowired
private RoleService roleService;
//查询所有角色
@RequestMapping("/role-list")
public Result roleList() {
return Result.ok(roleService.getAllRole());
}
}
我们某个用户已经有角色了,但是他并没有打上"√"
下面就来实现一下角色回显
// 根据userId查询对应角色
public List<Role> getRoleByUserId(@Param("userId") Integer userId);
<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>
@Override
public List<Role> getRoleByUserId(Integer userId) {
return roleMapper.getRoleByUserId(userId);
}
@Autowired
private RoleService roleService;
// 获取用户已经分配的角色
@RequestMapping("/user-role-list/{userId}")
public Result userRoleList(@PathVariable("userId") Integer userId){
return Result.ok(roleService.getRoleByUserId(userId));
}
处理的逻辑也很简单,把之前分配的角色删除,然后重新分配,这样就不用判断用户是否有某个角色了
/**
* 接收给用户分配角色前端传递的数据的Dto类:
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class AssignRoleDto {
//接收请求参数userId -- 用户id
private Integer userId;
//接收请求参数roleCheckList -- 给用户分配的所有角色名
private List<String> roleCheckList;
}
①根据角色名查询角色id
// 根据角色名查询角色id
public Integer findRoleIdByName(String roleName);
<select id="findRoleIdByName" resultType="java.lang.Integer">
select role.role_id
from role
where role.role_name = #{roleName}
select>
②删除已经用户分配的角色
删除关系表的信息即可
// 根据用户Id删除用户已经分配的角色关系
public int removeUserRoleByUid(Integer userId);
<delete id="removeUserRoleByUid">
delete
from user_role
where user_id = #{userId}
delete>
③向user_role表添加用户角色对应关系
// 向user_role表添加用户角色对应关系
public int insertUserRole(@Param("userId") Integer userId,@Param("roleId")Integer roleId);
<insert id="insertUserRole">
insert into user_role values(null,#{roleId},#{userId})
insert>
// 给用户修改角色信息
@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("更改角色成功");
}
// 给用户分配角色
@RequestMapping("/assignRole")
public Result assignRole(@RequestBody AssignRoleDto assignRoleDto){
return userService.changeUserRole(assignRoleDto);;
}