微服务项目:尚融宝(17)(后端搭建:数据字典)

本文涉及的产品
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
MSE Nacos/ZooKeeper 企业版试用,1600元额度,限量50份
云原生网关 MSE Higress,422元/月
简介: 微服务项目:尚融宝(17)(后端搭建:数据字典)

放弃幻想,认清现实,准备斗争


需求




cbdaff718c9e456e932c7b49cb3e63c9.png


一、什么是数据字典



何为数据字典?数据字典负责管理系统常用的分类数据或者一些固定数据,例如:省市区三级联动数据、民族数据、行业数据、学历数据等,数据字典帮助我们方便的获取和适用这些通用数据。


二、数据字典的设计




0cbb5b4c7d5e495f89992a6412649f1d.png


  • parent_id:上级id,通过id与parent_id构建上下级关系,例如:我们要获取所有行业数据,那么只需要查询parent_id=20000的数据
  • name:名称,例如:填写用户信息,我们要select标签选择民族,“汉族”就是数据字典的名称
  • value:值,例如:填写用户信息,我们要select标签选择民族,“1”(汉族的标识)就是数据字典的值
  • dict_code:编码,编码是我们自定义的,全局唯一,例如:我们要获取行业数据,我们可以通过parent_id获取,但是parent_id是不确定的,所以我们可以根据编码来获取行业数据


这样子的设置避免了多表的雍余


Excel数据批量导入



1、添加依赖


core中添加如下依赖


<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.xmlbeans</groupId>
    <artifactId>xmlbeans</artifactId>
</dependency>



2、创建Excel实体类


@Data
public class ExcelDictDTO {
    @ExcelProperty("id")
    private Long id;
    @ExcelProperty("上级id")
    private Long parentId;
    @ExcelProperty("名称")
    private String name;
    @ExcelProperty("值")
    private Integer value;
    @ExcelProperty("编码")
    private String dictCode;
}



3、创建监听器


@Slf4j
//@AllArgsConstructor //全参
@NoArgsConstructor //无参
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {
    /**
     * 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    List<ExcelDictDTO> list = new ArrayList();
    private DictMapper dictMapper;
  //传入mapper对象
    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }
    /**
     *遍历每一行的记录
     * @param data
     * @param context
     */
    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext context) {
        log.info("解析到一条记录: {}", data);
        list.add(data);
        // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }
    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据,确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成!");
    }
    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据,开始存储数据库!", list.size());
        dictMapper.insertBatch(list);  //批量插入
        log.info("存储数据库成功!");
    }
}



4、Mapper层批量插入


接口:DictMapper


void importData(InputStream inputStream);


实现:DictServiceImpl


@Transactional(rollbackFor = {Exception.class})
@Override
public void importData(InputStream inputStream) {
    // 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
    EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(baseMapper)).sheet().doRead();
    log.info("importData finished");
}


注意:此处添加了事务处理,默认情况下rollbackFor = RuntimeException.class 。能保证发现错误或者异常情况出现以后,能及时的回滚。避免数据的不正确


6、Controller层接收客户端上传


AdminDictController


@Api(tags = "数据字典管理")
@RestController
@RequestMapping("/admin/core/dict")
@Slf4j
@CrossOrigin
public class AdminDictController {
    @Resource
    private DictService dictService;
    @ApiOperation("Excel批量导入数据字典")
    @PostMapping("/import")
    public R batchImport(
            @ApiParam(value = "Excel文件", required = true)
            @RequestParam("file") MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            dictService.importData(inputStream);
            return R.ok().message("批量导入成功");
        } catch (Exception e) {
            //UPLOAD_ERROR(-103, "文件上传错误"),
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
        }
    }
}



7、添加mapper发布配置


注意:因为maven工程在默认情况下src/main/java目录下的所有资源文件是不发布到target目录下的,因此我们需要在pom.xml中添加xml配置文件发布配置


<build>
    <!-- 项目打包时会将java目录中的*.xml文件也进行打包 -->
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>



二、前端调用



1、创建页面组件


创建 src/views/core/dict/list.vue


<template>
  <div class="app-container">
  </div>
</template>
<script>
export default {
}
</script>



2、配置路由


{
    path: '/core',
    component: Layout,
    redirect: '/core/dict/list',
    name: 'coreDict',
    meta: { title: '系统设置', icon: 'el-icon-setting' },
    alwaysShow: true,
    children: [
      {
        path: 'dict/list',
        name: '数据字典',
        component: () => import('@/views/core/dict/list'),
        meta: { title: '数据字典' }
      }
    ]
},



3、实现数据导入


<template>
  <div class="app-container">
    <div style="margin-bottom: 10px;">
      <el-button
        @click="dialogVisible = true"
        type="primary"
        size="mini"
        icon="el-icon-download"
      >
        导入Excel
      </el-button>
      <el-button
    @click="exportData"
    type="primary"
    size="mini"
    icon="el-icon-upload2" >导出Excel</el-button>
    </div>
    <el-dialog title="数据字典导入" :visible.sync="dialogVisible" width="30%">
      <el-form>
        <el-form-item label="请选择Excel文件">
          <el-upload
            :auto-upload="true"
            :multiple="false"
            :limit="1"
            :on-exceed="fileUploadExceed"
            :on-success="fileUploadSuccess"
            :on-error="fileUploadError"
            :action="BASE_API + '/admin/core/dict/import'"
            name="file"
            accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>                                                                                                                                                                                           
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>
    <el-table :data="list" border row-key="id" lazy :load="load">
    <el-table-column label="名称" align="left" prop="name" />
    <el-table-column label="编码" prop="dictCode" />
    <el-table-column label="值" align="left" prop="value" />
</el-table>
  </div>
</template>
<script>
import dictApi from '@/api/core/dict'
export default {
  created() {
    console.log("123231231")
    this.fetchData()
},
  // 定义数据
  data() {
    return {
      dialogVisible: false, //文件上传对话框是否显示
      BASE_API: process.env.VUE_APP_BASE_API ,//获取后端接口地址
      list: [],//数据字典列表
    }
  },
  methods: {
    // 调用api层获取数据库中的数据
fetchData() {
  dictApi.listByParentId(1).then(response => {
     console.log("8888888888")
    this.list = response.data.list
  })
},
//延迟加载子节点
getChildren(row, treeNode, resolve) {
  dictApi.listByParentId(row.id).then(response => {
    //负责将子节点数据展示在展开的列表中  
    resolve(response.data.list)
  })
},
    // 上传多于一个文件时
    fileUploadExceed() {
      this.$message.warning('只能选取一个文件')
    },
//上传成功回调
fileUploadSuccess(response) {
    if (response.code === 0) {
        this.$message.success('数据导入成功')
        this.dialogVisible = false
        this.fetchData()
    } else {
        this.$message.error(response.message)
    }
},
    //上传失败回调
    fileUploadError(error) {
      this.$message.error('数据导入失败')
    },
    //Excel数据导出
exportData() {
    window.location.href = this.BASE_API + '/admin/core/dict/export'
},
//加载节点
load(tree,treeNode,resolve){
    //获取数据
    dictApi.listByParentId(tree.id).then(response => {
    resolve(response.data.list)
  })
  }
  }
}
</script>



Excel数据批量导出



1、Service层解析Excel数据


接口:DictService


List<ExcelDictDTO> listDictData();


实现:DictServiceImpl


@Override
public List<ExcelDictDTO> listDictData() {
    List<Dict> dictList = baseMapper.selectList(null);
    //创建ExcelDictDTO列表,将Dict列表转换成ExcelDictDTO列表
    ArrayList<ExcelDictDTO> excelDictDTOList = new ArrayList<>(dictList.size());
    dictList.forEach(dict -> {
        ExcelDictDTO excelDictDTO = new ExcelDictDTO();
        BeanUtils.copyProperties(dict, excelDictDTO);
        excelDictDTOList.add(excelDictDTO);
    });
    return excelDictDTOList;
}



2、Controller层接收客户端请求


@ApiOperation("Excel数据的导出")
@GetMapping("/export")
public void export(HttpServletResponse response){
    try {
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("mydict", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ExcelDictDTO.class).sheet("数据字典").doWrite(dictService.listDictData());
    } catch (IOException e) {
        //EXPORT_DATA_ERROR(104, "数据导出失败"),
        throw  new BusinessException(ResponseEnum.EXPORT_DATA_ERROR, e);
    }    
}



二、前端调用



1、页面添加导出按钮


<el-button
    @click="exportData"
    type="primary"
    size="mini"
    icon="el-icon-upload2" >导出Excel</el-button>


2、添加导出方法


//Excel数据导出
exportData() {
    window.location.href = this.BASE_API + '/admin/core/dict/export'
}



数据字典列表展示



一、后端接口


1、实体类添加属性


Dict中添加属性


@ApiModelProperty(value = "是否包含子节点")
@TableField(exist = false)//在数据库表中忽略此列
private boolean hasChildren;



2、Service层实现数据查询


接口:DictService


List<Dict> listByParentId(Long parentId);


实现:DictServiceImpl


@Override
public List<Dict> listByParentId(Long parentId) {
    List<Dict> dictList = baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", parentId));
    dictList.forEach(dict -> {
        //如果有子节点,则是非叶子节点
        boolean hasChildren = this.hasChildren(dict.getId());
        dict.setHasChildren(hasChildren);
    });
    return dictList;
}
/**
     * 判断该节点是否有子节点
     */
private boolean hasChildren(Long id) {
    QueryWrapper<Dict> queryWrapper = new QueryWrapper<Dict>().eq("parent_id", id);
    Integer count = baseMapper.selectCount(queryWrapper);
    if(count.intValue() > 0) {
        return true;
    }
    return false;
}



3、Controller层接收前端请求


@ApiOperation("根据上级id获取子节点数据列表")
@GetMapping("/listByParentId/{parentId}")
public R listByParentId(
    @ApiParam(value = "上级节点id", required = true)
    @PathVariable Long parentId) {
    List<Dict> dictList = dictService.listByParentId(parentId);
    return R.ok().data("list", dictList);
}



二、前端调用



1、api


创建 src/api/core/dict.js


import request from '@/utils/request'
export default {
  listByParentId(parentId) {
    return request({
      url: `/admin/core/dict/listByParentId/${parentId}`,
      method: 'get'
    })
  }
}



2、组件脚本


定义data


list: [], //数据字典列表


生命周期函数


created() {
    this.fetchData()
},



获取数据的方法


import dictApi from '@/api/core/dict'
// 调用api层获取数据库中的数据
fetchData() {
  dictApi.listByParentId(1).then(response => {
    this.list = response.data.list
  })
},
//延迟加载子节点
getChildren(row, treeNode, resolve) {
  dictApi.listByParentId(row.id).then(response => {
    //负责将子节点数据展示在展开的列表中  
    resolve(response.data.list)
  })
},



3、组件模板


<el-table :data="list" border row-key="id" lazy :load="load">
    <el-table-column label="名称" align="left" prop="name" />
    <el-table-column label="编码" prop="dictCode" />
    <el-table-column label="值" align="left" prop="value" />
</el-table>



4、流程优化


数据导入后刷新页面的数据列表


//上传成功回调
fileUploadSuccess(response) {
    if (response.code === 0) {
        this.$message.success('数据导入成功')
        this.dialogVisible = false
        this.fetchData()
    } else {
        this.$message.error(response.message)
    }
},



今日异常


java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use


问题有可能是有两个:


1.没有写启动类:
2.虽然写了启动类但是启动类所在的包和单元测试的包不在同一级根目录下。

如:一个是在cn.xxxx.cmcc,另一个是在cn.xxxxx,他们不在同一个目录下所以报 找不到启动类:
放在同一个包目录下就解决这个问题了。

总结:单元测试的测试类一定要和启动类在同一个根目录下。
 


相关文章
|
6月前
|
Java 测试技术 微服务
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
本课主要讲解Spring Boot项目中的属性配置方法。在实际开发中,测试与生产环境的配置往往不同,因此不应将配置信息硬编码在代码中,而应使用配置文件管理,如`application.yml`。例如,在微服务架构下,可通过配置文件设置调用其他服务的地址(如订单服务端口8002),并利用`@Value`注解在代码中读取这些配置值。这种方式使项目更灵活,便于后续修改和维护。
88 0
|
6月前
|
Java 微服务 Spring
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录——使用Logger在项目中打印日志
本文介绍了如何在项目中使用Logger打印日志。通过SLF4J和Logback,可设置不同日志级别(如DEBUG、INFO、WARN、ERROR)并支持占位符输出动态信息。示例代码展示了日志在控制器中的应用,说明了日志配置对问题排查的重要性。附课程源码下载链接供实践参考。
672 0
|
4月前
|
Java 关系型数据库 MySQL
在Linux平台上进行JDK、Tomcat、MySQL的安装并部署后端项目
现在,你可以通过访问http://Your_IP:Tomcat_Port/Your_Project访问你的项目了。如果一切顺利,你将看到那绚烂的胜利之光照耀在你的项目之上!
288 41
|
5月前
|
人工智能 小程序 NoSQL
【一步步开发AI运动小程序】二十一、如何将AI运动项目配置持久化到后端?
本文介绍基于云智「Ai运动识别引擎」的运动配置持久化方案,旨在优化小程序或Uni APP中AI运动识别能力。通过将运动检测参数(如`Key`、`Name`、`TickMode`、`rules`或`samples`)持久化到后端,可避免因频繁调整运动参数而重新发布应用,提升用户体验。持久化数据结构支持规则和姿态样本存储,适用于关系数据库、文件或文档数据库(如MongoDB)。此外,云智还提供运动自动适配工具及「AI乐运动」产品,助力快速实现AI体育、全民健身等场景。
|
6月前
|
Java 数据库 微服务
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——指定项目配置文件
在实际项目中,开发环境和生产环境的配置往往不同。为简化配置切换,可通过创建 `application-dev.yml` 和 `application-pro.yml` 分别管理开发与生产环境配置,如设置不同端口(8001/8002)。在 `application.yml` 中使用 `spring.profiles.active` 指定加载的配置文件,实现环境快速切换。本节还介绍了通过配置类读取参数的方法,适用于微服务场景,提升代码可维护性。课程源码可从 [Gitee](https://gitee.com/eson15/springboot_study) 下载。
215 0
|
6月前
|
Java 微服务 Spring
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
在微服务架构中,随着业务复杂度增加,项目可能需要调用多个微服务。为避免使用`@Value`注解逐一引入配置的繁琐,可通过定义配置类(如`MicroServiceUrl`)并结合`@ConfigurationProperties`注解实现批量管理。此方法需在配置文件中设置微服务地址(如订单、用户、购物车服务),并通过`@Component`将配置类纳入Spring容器。最后,在Controller中通过`@Resource`注入配置类即可便捷使用,提升代码可维护性。
93 0
|
10月前
|
设计模式 Java API
微服务架构演变与架构设计深度解析
【11月更文挑战第14天】在当今的IT行业中,微服务架构已经成为构建大型、复杂系统的重要范式。本文将从微服务架构的背景、业务场景、功能点、底层原理、实战、设计模式等多个方面进行深度解析,并结合京东电商的案例,探讨微服务架构在实际应用中的实施与效果。
519 6
|
10月前
|
设计模式 Java API
微服务架构演变与架构设计深度解析
【11月更文挑战第14天】在当今的IT行业中,微服务架构已经成为构建大型、复杂系统的重要范式。本文将从微服务架构的背景、业务场景、功能点、底层原理、实战、设计模式等多个方面进行深度解析,并结合京东电商的案例,探讨微服务架构在实际应用中的实施与效果。
242 1
|
9月前
|
Java 开发者 微服务
从单体到微服务:如何借助 Spring Cloud 实现架构转型
**Spring Cloud** 是一套基于 Spring 框架的**微服务架构解决方案**,它提供了一系列的工具和组件,帮助开发者快速构建分布式系统,尤其是微服务架构。
642 71
从单体到微服务:如何借助 Spring Cloud 实现架构转型
|
12月前
|
安全 应用服务中间件 API
微服务分布式系统架构之zookeeper与dubbo-2
微服务分布式系统架构之zookeeper与dubbo-2