数据字典工程化实现与字段映射规范
在软件开发过程中,数据字典作为基础组件对系统一致性至关重要。以下为实际工程中常用的设计模式与实现方案。
数据库字典表设计 采用两表结构实现字典管理:
| 主表 | 字段 |
|---|---|
| id | 唯一标识 |
| type_code | 类型编码 |
| type_name | 类型名称 |
| 明细表 | 字段 |
|---|---|
| id | 唯一标识 |
| parent_id | 关联主表id |
| value_code | 值编码 |
| display_name | 展示名称 |
字典数据缓存策略 为避免频繁数据库查询,采用Redis缓存机制:
- 系统启动时加载字典数据至Redis
- 字典数据变更时清除对应Redis键
- 后续请求直接从缓存获取
静态字典映射实现 当无需数据库支持时,可采用静态映射方案:
字典条目定义
public class DictionaryEntry {
private String valueCode;
private String displayName;
private boolean isDeleted;
public DictionaryEntry(String code, String name, boolean deleted) {
this.valueCode = code;
this.displayName = name;
this.isDeleted = deleted;
}
// 省略getter/setter
}
字典工具类
public class DictionaryHelper {
private static final Map<String, DictionaryEntry> STATUS_MAP = new HashMap<>();
static {
STATUS_MAP.put("0", new DictionaryEntry("0", "Active", false));
STATUS_MAP.put("1", new DictionaryEntry("1", "Deleted", true));
}
public static String getValueDisplay(Map<String, DictionaryEntry> dictMap, String value) {
if (value == null || value.isEmpty()) return "";
DictionaryEntry entry = dictMap.get(value);
return entry != null ? entry.getDisplayName() : value;
}
public static String getDisplayValue(Map<String, DictionaryEntry> dictMap, String display) {
if (display == null || display.isEmpty()) return "";
for (Map.Entry<String, DictionaryEntry> entry : dictMap.entrySet()) {
if (display.equals(entry.getValue().getDisplayName())) {
return entry.getKey();
}
}
return display;
}
}
映射使用场景规范
| 操作类型 | 数据流向 | 映射方向 |
|---|---|---|
| 查询 | 数据库code → 前端展示 | code→name |
| 新增/编辑 | 前端传入code | 无需映射 |
| 导出 | 后端生成文件内容 | code→name |
| 导入 | 前端传入name → 后端处理 | name→code |
字段注释规范 推荐采用结构化注释格式:
状态[0:Active,1:Deleted]
- 优先使用冒号分隔值与显示文本
- 避免使用连字符(-)防止中文字段混淆
- 接口文档可简化为:
状态
0: Active
1: Deleted
输入输出字段类型
| 输入类型 | 示例 |
|---|---|
| 普通文本 | String/Number |
| 字典值 | STATUS_CODE |
| 区间范围 | 2023-01-01~2023-12-31 |
| 列表结构 | List |
| 输出类型 | 示例 |
|---|---|
| 普通文本 | String/Number |
| 字典映射 | 显示名称 |
| 树形结构 | Tree |
DTO设计原则 Data Transfer Object (DTO)用于解决不同层间数据结构差异:
- 实体类(Entity):对应数据库表结构
- DTO:作为数据传输中间层,仅包含必要字段
- 批量操作对象(如InvoiceBatch):明确标识用途 DTO设计需确保:
- 仅包含传输所需字段
- 结构清晰避免冗余
- 与业务场景强关联