『博客开发日记-后台』之添加字典项接口的实现

本文最后更新于 2026年5月24日 晚上

添加字典项接口的实现


添加字典项接口的需求

检查同一个字典编码(dict_code)下的字典项标签(label)和字典项值(value)是否重复


代码实现

在 DeptController 中添加接口

1
2
3
4
5
6
7
8
@PostMapping("/{dictCode}/items")
@PreAuthorize("@ps.hasPermission('blog:dict:create')")
@SystemLog(businessName = "新增字典项")
@ApiOperation(value = "新增字典项接口", notes = "新增字典项", response = String.class)
public ResponseResult addDictItem(@PathVariable String dictCode, @Valid @RequestBody AddDictItemDto addDictItemDto)
{
return sysDictItemService.addDictItem(dictCode, addDictItemDto);
}

创建 AddDictItemDto

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
/**
* 添加字典项请求DTO
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(description = "添加字典项请求对象")
public class AddDictItemDto {

@NotBlank(message = "字典项标签不能为空")
@ApiModelProperty(value = "字典项标签", required = true, example = "男")
private String label;

@NotBlank(message = "字典项值不能为空")
@ApiModelProperty(value = " 字典项值", required = true, example = "1")
private String value;

@ApiModelProperty(value = "排序", example = "1")
private Integer sort;

@ApiModelProperty(value = "标签类型,用于前端样式展示:`success`/`warning`/`info`/`primary`/`danger`/空", example = "success")
private String tagType;

@NotBlank(message = "状态不能为空")
@Pattern(regexp = "^[01]$", message = "状态只能为0或1")
@ApiModelProperty(value = "状态(0-正常,1-禁用)", required = true, example = "0")
private String status;
}


在 SysDictItemServiceImpl 中

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
 //添加字典项
@Override
public ResponseResult addDictItem(String dictCode, AddDictItemDto addDictItemDto)
{
//检查同一个字典编码(dict_code)下的字典项标签(label)和字典项值(value)是否重复
LambdaQueryWrapper<SysDictItem> labelWrapper = new LambdaQueryWrapper<>();
labelWrapper.eq(SysDictItem::getDictCode, dictCode)
.eq(SysDictItem::getLabel, addDictItemDto.getLabel());
long labelCount = sysDictItemService.count(labelWrapper);
if (labelCount > 0) {
return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "当前字典下字典项标签已存在,请勿重复添加!");
}

LambdaQueryWrapper<SysDictItem> valueWrapper = new LambdaQueryWrapper<>();
valueWrapper.eq(SysDictItem::getDictCode, dictCode)
.eq(SysDictItem::getValue, addDictItemDto.getValue());
long valueCount = sysDictItemService.count(valueWrapper);
if (valueCount > 0) {
return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "当前字典下字典项值已存在,请勿重复添加!");
}

//添加字典项
SysDictItem dictItem = BeanCopyUtils.copyBean(addDictItemDto, SysDictItem.class);
dictItem.setDictCode(dictCode);
sysDictItemService.save(dictItem);

return ResponseResult.okResult();
}

需要注意的是

为了避免重复代码过多

我将 获取当前用户拥有的数据权限范围 相关的代码提取出来成 applyDeptDataScopeFilter 方法方便调用了

并且在 AdminUserServiceImpl 中也进行了类似的操作




PS:该系列只做为作者学习开发项目做的笔记用

不一定符合读者来学习,仅供参考


预告

后续会记录博客的开发过程

每次学习会做一份笔记来进行发表

“一花一世界,一叶一菩提”


版权所有 © 2026 云梦泽
欢迎访问我的个人网站:https://hgt12.github.io/


『博客开发日记-后台』之添加字典项接口的实现
http://example.com/2026/05/24/『博客开发日记-后台』之添加字典项接口的实现/
作者
云梦泽
发布于
2026年5月24日
更新于
2026年5月24日
许可协议