本文最后更新于 2026年5月24日 下午
添加部门接口的实现
添加部门接口的需求
检测部门名称与部门编号是否已经纯在
添加父节点路径:根节点为 0,子节点为 父节点路径,父节点ID
顶级部门设置 treePath
如果当前部门是顶级部门直接赋值 0
如果不是顶级部门就先查父部门是否存在
再取父部门的路径再用","拼接出当前部门完整的层级路径
代码实现
DeptController
1 2 3 4 5 6 7 8
| @PostMapping @PreAuthorize("@ps.hasPermission('blog:dept:create')") @SystemLog(businessName = "新增部门接口") @ApiOperation(value = "新增部门接口", notes = "新增部门", response = String.class) public ResponseResult addDept(@Valid @RequestBody AddDeptDto addDeptDto) { return sysDeptService.addDept(addDeptDto); }
|
创建 AddDeptDto
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
|
@Data @AllArgsConstructor @NoArgsConstructor @ApiModel(description = "添加部门请求对象") public class AddDeptDto {
@NotBlank(message = "部门名称不能为空") @ApiModelProperty(value = "部门名称", required = true, example = "技术部") private String name;
@ApiModelProperty(value = "部门编码", example = "TECH") private String code;
@NotNull(message = "上级部门不能为空") @ApiModelProperty(value = "父部门ID(顶级部门可传'0')", required = true, example = "1") private Long parentId;
@ApiModelProperty(value = "排序值", example = "0") private Integer sort;
@NotBlank(message = "状态不能为空") @Pattern(regexp = "^[01]$", message = "状态只能为0或1") @ApiModelProperty(value = "状态(0-正常,1-禁用)", required = true, example = "0") private String status; }
|
添加常量
1 2 3 4
|
public static final String PARENT_NODE_PATH = "0";
|
在 SysDeptServiceImpl 中实现功能
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
| @Override public ResponseResult addDept(AddDeptDto addDeptDto) { LambdaQueryWrapper<SysDept> nameWrapper = new LambdaQueryWrapper<>(); nameWrapper.eq(SysDept::getName, addDeptDto.getName()); if (sysDeptService.count(nameWrapper) > 0) { return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "部门名称已存在,请勿重复添加!"); }
LambdaQueryWrapper<SysDept> codeWrapper = new LambdaQueryWrapper<>(); codeWrapper.eq(SysDept::getCode, addDeptDto.getCode()); if (sysDeptService.count(codeWrapper) > 0) { return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "部门编号已存在,请勿重复添加!"); }
SysDept sysDept = BeanCopyUtils.copyBean(addDeptDto, SysDept.class); Long parentId = addDeptDto.getParentId(); sysDept.setParentId(parentId);
if (Objects.equals(parentId, 0L)) { sysDept.setTreePath(SystemConstants.PARENT_NODE_PATH); } else { SysDept parentDept = sysDeptService.getById(parentId); if (parentDept == null) { return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "上级部门不存在!"); } String parentTreePath = parentDept.getTreePath(); if (parentTreePath == null || parentTreePath.isBlank()) { parentTreePath = SystemConstants.PARENT_NODE_PATH; } sysDept.setTreePath(parentTreePath + "," + parentDept.getId()); }
sysDeptService.save(sysDept);
return ResponseResult.okResult(); }
|
PS:该系列只做为作者学习开发项目做的笔记用
不一定符合读者来学习,仅供参考
预告
后续会记录博客的开发过程
每次学习会做一份笔记来进行发表
“一花一世界,一叶一菩提”
版权所有 © 2026 云梦泽
欢迎访问我的个人网站:https://hgt12.github.io/