jeecg-boot字典翻译改造(支持实体类详情查询自动翻译)

本文介绍了一种针对字典切面类的改造方法,重点在于支持自动翻译代码生成,适用于列表接口及单个实体类查询。该方法通过解析实体类字段,实现字典字段的自动翻译,并对日期类型字段进行格式化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 找到字典切面类(DictAspect)

  2. 改造方法(parseDictText)

支持自动生成的列表接口/单个实体类查询翻译
代码如下:

private void parseDictText(Object result) {
        if (result instanceof Result) {
            if (((Result) result).getResult() instanceof IPage) {
                List<JSONObject> items = new ArrayList<>();
                for (Object record : ((IPage) ((Result) result).getResult()).getRecords()) {
                    ObjectMapper mapper = new ObjectMapper();
                    String json = "{}";
                    try {
                        //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                        json = mapper.writeValueAsString(record);
                    } catch (JsonProcessingException e) {
                        log.error("json解析失败" + e.getMessage(), e);
                    }
                    JSONObject item = JSONObject.parseObject(json);
                    //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                    //for (Field field : record.getClass().getDeclaredFields()) {
                    for (Field field : oConvertUtils.getAllFields(record)) {
                        //update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                        if (field.getAnnotation(Dict.class) != null) {
                            String code = field.getAnnotation(Dict.class).dicCode();
                            String text = field.getAnnotation(Dict.class).dicText();
                            String table = field.getAnnotation(Dict.class).dictTable();
                            String key = String.valueOf(item.get(field.getName()));

                            //翻译字典值对应的txt
                            String textValue = translateDictValue(code, text, table, key);

                            log.debug(" 字典Val : " + textValue);
                            log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
                            item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                        }
                        //date类型默认转换string格式化日期
                        if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                            SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                        }
                    }
                    items.add(item);
                }
                ((IPage) ((Result) result).getResult()).setRecords(items);
            } else {
                Object record = (Object) ((Result) result).getResult();
                ObjectMapper mapper = new ObjectMapper();
                String json = "{}";
                try {
                    //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                    json = mapper.writeValueAsString(record);
                } catch (JsonProcessingException e) {
                    log.error("json解析失败" + e.getMessage(), e);
                }
                try {
                    JSONObject item = JSONObject.parseObject(json);
                    //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                    //for (Field field : record.getClass().getDeclaredFields()) {
                    for (Field field : oConvertUtils.getAllFields(record)) {
                        //update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                        if (field.getAnnotation(Dict.class) != null) {
                            String code = field.getAnnotation(Dict.class).dicCode();
                            String text = field.getAnnotation(Dict.class).dicText();
                            String table = field.getAnnotation(Dict.class).dictTable();
                            String key = String.valueOf(item.get(field.getName()));

                            //翻译字典值对应的txt
                            String textValue = translateDictValue(code, text, table, key);

                            log.debug(" 字典Val : " + textValue);
                            log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
                            item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                        }
                        //date类型默认转换string格式化日期
                        if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                            SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                        }
                    }
//                }
                    ((Result) result).setResult(item);
                }catch (Exception e){
                    log.info("########################此返回类型不支持字典翻译########################");
                }
            }
        }
    }

单个查询返回数据格式样例:

/**
 * 通过id查询
 *
 * @param id
 * @return
 */

@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
   ShgBanner shgBanner = shgBannerService.getById(id);
   if(shgBanner==null) {
      return Result.error("未找到对应数据");
   }
   return Result.ok(shgBanner);
}

第二版改造 : 2023/2/22

总结:

  1. 支持单个实体类解析
  2. 支持实体类集合解析
  3. 支持过滤基本类型集合不进行解析, 暂时过滤了三种 java.lang.String java.lang.long java.lang.Integer

完整方法如下 :

private void parseDictTextOne(Object result) {
        if (result instanceof Result) {
            if (((Result) result).getResult() instanceof IPage) {
                List<JSONObject> items = new ArrayList<>();
                for (Object record : ((IPage) ((Result) result).getResult()).getRecords()) {
                    ObjectMapper mapper = new ObjectMapper();
                    String json = "{}";
                    try {
                        //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                        json = mapper.writeValueAsString(record);
                    } catch (JsonProcessingException e) {
                        log.error("json解析失败" + e.getMessage(), e);
                    }
                    JSONObject item = JSONObject.parseObject(json);
                    //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                    //for (Field field : record.getClass().getDeclaredFields()) {
                    for (Field field : oConvertUtils.getAllFields(record)) {
                        //update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                        if (field.getAnnotation(Dict.class) != null) {
                            String code = field.getAnnotation(Dict.class).dicCode();
                            String text = field.getAnnotation(Dict.class).dicText();
                            String table = field.getAnnotation(Dict.class).dictTable();
                            String key = String.valueOf(item.get(field.getName()));

                            //翻译字典值对应的txt
                            String textValue = translateDictValue(code, text, table, key);

                            log.debug(" 字典Val : " + textValue);
                            log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
                            item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                        }
                        //date类型默认转换string格式化日期
                        if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                            SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                        }
                    }
                    items.add(item);
                }
                ((IPage) ((Result) result).getResult()).setRecords(items);
            } else if (((Result) result).getResult() instanceof List) {
                List result1 = (List) ((Result) result).getResult();
                if (CollectionUtils.isNotEmpty(result1)) {
                    Class<?> aClass = result1.get(0).getClass();
                    String className = aClass.getName();
                    log.info("------- List<T> 泛型 T is {}", className);
                    //只解析result中list泛型是object的数据, 基本数据类型不解析
                    /**
                     * 以下类型不解析
                     * java.lang.String
                     * java.lang.long
                     * java.lang.Integer
                     */
                    if (!className.equals("java.lang.String") && !className.equals("java.lang.long") && !className.equals("java.lang.Integer")) {
                        List<JSONObject> items = new ArrayList<>();
                        for (Object record : (List) ((Result) result).getResult()) {
                            ObjectMapper mapper = new ObjectMapper();
                            String json = "{}";
                            try {
                                //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                                json = mapper.writeValueAsString(record);
                            } catch (JsonProcessingException e) {
                                log.error("json解析失败" + e.getMessage(), e);
                            }
                            JSONObject item = JSONObject.parseObject(json);
                            //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                            //for (Field field : record.getClass().getDeclaredFields()) {
                            for (Field field : oConvertUtils.getAllFields(record)) {
                                //update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                                if (field.getAnnotation(Dict.class) != null) {
                                    String code = field.getAnnotation(Dict.class).dicCode();
                                    String text = field.getAnnotation(Dict.class).dicText();
                                    String table = field.getAnnotation(Dict.class).dictTable();
                                    String key = String.valueOf(item.get(field.getName()));

                                    //翻译字典值对应的txt
                                    String textValue = translateDictValue(code, text, table, key);

                                    log.debug(" 字典Val : " + textValue);
                                    log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
                                    item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                                }
                                //date类型默认转换string格式化日期
                                if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                                    SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                                }
                            }
                            items.add(item);
                        }
                        ((Result) result).setResult(items);
                    }else {
                        log.info("只解析result中list<T>泛型是实体类的数据, 基本数据类型不解析: T is {}", className);
                    }
                }else {
                    log.info(" result中List<T> 为空,跳过不解析 ");
                }

            } else {
                Object record = (Object) ((Result) result).getResult();
                ObjectMapper mapper = new ObjectMapper();
                String json = "{}";
                try {
                    //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                    json = mapper.writeValueAsString(record);
                } catch (JsonProcessingException e) {
                    log.error("json解析失败" + e.getMessage(), e);
                }
                try {
                    JSONObject item = JSONObject.parseObject(json);
                    //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                    //for (Field field : record.getClass().getDeclaredFields()) {
                    for (Field field : oConvertUtils.getAllFields(record)) {
                        //update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                        if (field.getAnnotation(Dict.class) != null) {
                            String code = field.getAnnotation(Dict.class).dicCode();
                            String text = field.getAnnotation(Dict.class).dicText();
                            String table = field.getAnnotation(Dict.class).dictTable();
                            String key = String.valueOf(item.get(field.getName()));

                            //翻译字典值对应的txt
                            String textValue = translateDictValue(code, text, table, key);

                            log.debug(" 字典Val : " + textValue);
                            log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
                            item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                        }
                        //date类型默认转换string格式化日期
                        if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                            SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                        }
                    }
                    ((Result) result).setResult(item);
                } catch (Exception e) {
                    log.info("########################此返回类型不支持字典翻译########################");
                }
            }
        }
    }

改造部分如下 :

else if (((Result) result).getResult() instanceof List) {
                List result1 = (List) ((Result) result).getResult();
                if (CollectionUtils.isNotEmpty(result1)) {
                    Class<?> aClass = result1.get(0).getClass();
                    String className = aClass.getName();
                    log.info("------- List<T> 泛型 T is {}", className);
                    //只解析result中list泛型是object的数据, 基本数据类型不解析
                    /**
                     * 以下类型不解析
                     * java.lang.String
                     * java.lang.long
                     * java.lang.Integer
                     */
                    if (!className.equals("java.lang.String") && !className.equals("java.lang.long") && !className.equals("java.lang.Integer")) {
                        List<JSONObject> items = new ArrayList<>();
                        for (Object record : (List) ((Result) result).getResult()) {
                            ObjectMapper mapper = new ObjectMapper();
                            String json = "{}";
                            try {
                                //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                                json = mapper.writeValueAsString(record);
                            } catch (JsonProcessingException e) {
                                log.error("json解析失败" + e.getMessage(), e);
                            }
                            JSONObject item = JSONObject.parseObject(json);
                            //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                            //for (Field field : record.getClass().getDeclaredFields()) {
                            for (Field field : oConvertUtils.getAllFields(record)) {
                                //update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                                if (field.getAnnotation(Dict.class) != null) {
                                    String code = field.getAnnotation(Dict.class).dicCode();
                                    String text = field.getAnnotation(Dict.class).dicText();
                                    String table = field.getAnnotation(Dict.class).dictTable();
                                    String key = String.valueOf(item.get(field.getName()));

                                    //翻译字典值对应的txt
                                    String textValue = translateDictValue(code, text, table, key);

                                    log.debug(" 字典Val : " + textValue);
                                    log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
                                    item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                                }
                                //date类型默认转换string格式化日期
                                if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                                    SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                                }
                            }
                            items.add(item);
                        }
                        ((Result) result).setResult(items);
                    }else {
                        log.info("只解析result中list<T>泛型是实体类的数据, 基本数据类型不解析: T is {}", className);
                    }
                }else {
                    log.info(" result中List<T> 为空,跳过不解析 ");
                }

            } else {
                Object record = (Object) ((Result) result).getResult();
                ObjectMapper mapper = new ObjectMapper();
                String json = "{}";
                try {
                    //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                    json = mapper.writeValueAsString(record);
                } catch (JsonProcessingException e) {
                    log.error("json解析失败" + e.getMessage(), e);
                }
                try {
                    JSONObject item = JSONObject.parseObject(json);
                    //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                    //for (Field field : record.getClass().getDeclaredFields()) {
                    for (Field field : oConvertUtils.getAllFields(record)) {
                        //update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                        if (field.getAnnotation(Dict.class) != null) {
                            String code = field.getAnnotation(Dict.class).dicCode();
                            String text = field.getAnnotation(Dict.class).dicText();
                            String table = field.getAnnotation(Dict.class).dictTable();
                            String key = String.valueOf(item.get(field.getName()));

                            //翻译字典值对应的txt
                            String textValue = translateDictValue(code, text, table, key);

                            log.debug(" 字典Val : " + textValue);
                            log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
                            item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                        }
                        //date类型默认转换string格式化日期
                        if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                            SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                        }
                    }
                    ((Result) result).setResult(item);
                } catch (Exception e) {
                    log.info("########################此返回类型不支持字典翻译########################");
                }
            }

支持如下返回方式 :

// 单个实体解析
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
   ShgBanner shgBanner = shgBannerService.getById(id);
   if(shgBanner==null) {
      return Result.error("未找到对应数据");
   }
   return Result.ok(shgBanner);
}

// 列表实体解析
@GetMapping("/queryRawMaters")
public Result<?> queryRawMaters(){
	List<HgRawMaterial> rawMaterialList = hgFinishedProductSonService.queryRawMaters();
	return Result.OK(rawMaterialList);
}
Jeecg Boot是一个基于Spring Boot的企业级快速开发平台,它提供了一系列强大的功能,包括轻量级的微服务架构、权限管理系统、工作流引擎等。Ant Design Vue是基于Ant Design设计体系的Vue组件库。 如果你想要在Jeecg Boot项目中集成Ant Design Vue,并配置字典项(通常用于存储可选择的选项,如性别、角色等),可以按照以下步骤操作: 1. **添加依赖**:首先,在你的`pom.xml`文件中添加Ant Design Vue的依赖: ```xml <dependency> <groupId>com.azelcast</groupId> <artifactId>ant-design-vue</artifactId> <version>最新版本号</version> </dependency> ``` 记得替换为实际的版本号。 2. **全局注册组件**:在`application.yml`或`application.properties`中配置Vue组件的引入路径: ```yaml jeecg: vue: global-components-dir: classpath:/static/components/ ``` 这将允许你在模板文件中直接使用Ant Design Vue组件。 3. **创建字典表**:在数据库中创建一个表来存储字典项数据,例如`dict_table`,字段可能包括`id`, `code`, `name`, 等。 4. **实体模型映射**:创建一个Java实体类,比如`DictEntity`,并用它来映射数据库的字典表。 5. **注入字典服务**:在需要的地方,通过Jeecg提供的服务注入机制,注入一个处理字典数据的服务,例如`DictService`。 6. **获取和显示字典项**:在视图层,调用`DictService`的方法来获取特定类型的字典项,然后在前端展示给用户选择。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微微一笑满城空

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值