refactor(system): 优化用户管理相关代码

- 调整代码格式和缩进,提高可读性
- 重构用户角色关联逻辑,提取为独立方法- 更新用户更新 DTO,支持多角色选择
This commit is contained in:
zhuangtianxiang 2025-02-06 20:38:05 +08:00
parent e4bf57f3ec
commit b4da8c3bf0
2 changed files with 23 additions and 10 deletions

View File

@ -12,6 +12,9 @@ import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Pattern;
import java.util.List;
import java.util.Set;
/** /**
* 用户更新Dto * 用户更新Dto
* *
@ -59,11 +62,13 @@ public class UserUpdateDto {
public String address; public String address;
/** /**
* 用户身份集合 * 用户身份
*/ */
@NotEmpty(message = "角色不能为空") @NotEmpty(message = "角色不能为空")
public Long roleId; public Long roleId;
public String remark; public String remark;
public Set<Long> roleIds;
} }

View File

@ -58,15 +58,7 @@ public class UserServiceImpl extends ServiceImpl<UserRepository, User> implement
return false; return false;
} }
if (dto.getRoleIds() != null && !dto.getRoleIds().isEmpty()) { if (dto.getRoleIds() != null && !dto.getRoleIds().isEmpty()) {
List<UserRole> userRoles = dto.getRoleIds().stream() addUserRole(dto.getRoleIds(), user.getId());
.map(roleId -> {
UserRole userRole = new UserRole();
userRole.setUserId(user.getId());
userRole.setRoleId(roleId);
return userRole;
})
.collect(Collectors.toList());
userRolesRepository.insert(userRoles);
} }
return true; return true;
} }
@ -82,6 +74,10 @@ public class UserServiceImpl extends ServiceImpl<UserRepository, User> implement
if (user.getEmail().equals(dto.getEmail()) && existsByEmail) { if (user.getEmail().equals(dto.getEmail()) && existsByEmail) {
throw new ConstraintException("email", dto.email, "邮箱地址已存在"); throw new ConstraintException("email", dto.email, "邮箱地址已存在");
} }
if (dto.getRoleIds() != null && !dto.getRoleIds().isEmpty()) {
userRolesRepository.delete(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, id));
addUserRole(dto.getRoleIds(), user.getId());
}
BeanUtils.copyProperties(dto, user); BeanUtils.copyProperties(dto, user);
return updateById(user); return updateById(user);
} }
@ -159,4 +155,16 @@ public class UserServiceImpl extends ServiceImpl<UserRepository, User> implement
return userDetails; return userDetails;
} }
public Boolean addUserRole(Set<Long> roleIds, Long userId) {
List<UserRole> userRoles = roleIds.stream()
.map(roleId -> {
UserRole userRole = new UserRole();
userRole.setUserId(userId);
userRole.setRoleId(roleId);
return userRole;
})
.collect(Collectors.toList());
userRolesRepository.insert(userRoles);
return true;
}
} }