跳到主要内容

字典翻译注解

@Dict 字典翻译注解

@Dict 注解用于将数据库字段的值自动翻译为对应的字典文本,常用于列表展示。例如,字段 sex 存储值为 1,自动生成 sex_dictText 字段,值为“男”。

功能说明

通过 @Dict 注解,可将数据库某一列的值根据字典配置自动翻译为文字描述。

应用场景举例:

  • 用户表的性别字段 sex,数据库存储 1、2 分别表示男、女。通过 @Dict 注解,前端展示时可自动翻译为“男”“女”。

使用步骤

1. 配置字典

在系统字典管理中配置对应的字典项。例如:

  • 字典编码:sex
  • 字典项:1=男,2=女

2. 后端实体属性添加注解

在实体类字段上添加 @Dict 注解,dicCode 对应字典编码:

/**
* 性别(1:男 2:女)
*/
@Dict(dicCode = "sex")
private Integer sex;

3. 前端表格列配置

前端表格 columns 配置时,dataIndex 需使用“原字段名+_dictText”,如 sex_dictText:

columns: [
// ...其他列
{
title: '性别',
align: 'center',
width: 80,
dataIndex: 'sex_dictText',
},
]

4. 字典表翻译用法

如需从其他表动态获取字典数据,可指定 dictTable 和 dicText:

@Dict(dicCode = "id", dictTable = "sys_user", dicText = "realname")

5. 多数据源字典表配置

在微服务或多数据源场景下,若字典表不在主数据源,可通过 ds 参数指定数据源名称:

@Dict(dicCode = "id", dictTable = "sys_user", dicText = "realname", ds = "multi-datasource1")

说明:multi-datasource1 对应配置文件中的数据源名称。

常见问题

  • dicCode 必须与字典编码一致。
  • dataIndex 必须为“原字段名+_dictText”。
  • 多数据源时,确保 ds 参数配置正确。

@EnumDict 枚举字典

除了系统字典外,还可以将 Java 枚举类转化为系统字典数据,便于统一管理和前端展示。

定义枚举字典的步骤

为提升系统性能,v3.8.3+ 版本需手动配置字典枚举扫描路径。

  1. 新建枚举类,类名建议以 Enum 结尾,并在类上添加 @EnumDict 注解。
  2. 手动将枚举类所在包路径添加到 org.jeecg.common.system.util.ResourceUtil.BASE_SCAN_PACKAGES 配置数组中。

    [warning] 为提升系统性能,v3.8.3+ 版本需手动配置字典枚举扫描路径。

使用方法

在需要翻译的实体类字段上添加 @Dict(dicCode = "枚举value定义") 注解。例如,dicCode 的值为 messageType

示例枚举类

package org.jeecg.common.constant.enums;

import org.jeecg.common.system.annotation.EnumDict;
import org.jeecg.common.system.vo.DictModel;
import java.util.ArrayList;
import java.util.List;

/**
* 消息类型
*/
@EnumDict("messageType")
public enum MessageTypeEnum {
/** 系统消息 */
XT("system", "系统消息"),
/** 邮件消息 */
YJ("email", "邮件消息"),
/** 钉钉消息 */
DD("dingtalk", "钉钉消息"),
/** 企业微信 */
QYWX("wechat_enterprise", "企业微信");

private String type;
private String note;

MessageTypeEnum(String type, String note) {
this.type = type;
this.note = note;
}

public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getNote() { return note; }
public void setNote(String note) { this.note = note; }

/**
* 获取字典数据
*/
public static List<DictModel> getDictList() {
List<DictModel> list = new ArrayList<>();
for (MessageTypeEnum e : MessageTypeEnum.values()) {
DictModel dictModel = new DictModel();
dictModel.setValue(e.getType());
dictModel.setText(e.getNote());
list.add(dictModel);
}
return list;
}

/**
* 根据type获取枚举
*/
public static MessageTypeEnum valueOfType(String type) {
for (MessageTypeEnum e : MessageTypeEnum.values()) {
if (e.getType().equals(type)) {
return e;
}
}
return null;
}
}

示例实体类字段

@Dict(dicCode = "messageType")
private String messageType;

常见问题

  • 枚举类必须加 @EnumDict 注解,否则无法被扫描。
  • 枚举类所在包路径需加入 BASE_SCAN_PACKAGES,否则无法加载。
  • dicCode 必须与 @EnumDict 注解值一致。