烯八 发表于 2025-7-30 15:47:41

生成数据库的表结构文档

背景说明
项目完成前后,需要提供各种各样的文档,我所在的公司,每次项目结束要整理的文档高达29个,其中有些文档很单一但是数据量很大,这个时候就必须偷懒一下了。
使用依赖
<groupId>cn.smallbun.screw</groupId>
screw-core</artifactId>
<version>1.0.5</version>依赖说明
在企业级开发中、我们经常会有编写数据库表结构文档的时间付出,从业以来,待过几家企业,关于数据库表结构文档状态:要么没有、要么有、但都是手写、后期运维开发,需要手动进行维护到文档中,很是繁琐、如果忘记一次维护、就会给以后工作造成很多困扰、无形中制造了很多坑留给自己和后人,于是萌生了要自己写一个插件工具的想法,但由于自己前期在程序设计上没有很多造诣,且能力偏低,有想法并不能很好实现,随着工作阅历的增加,和知识的不断储备,终于在2020年的3月中旬开始进行编写,4月上旬完成初版,想完善差不多在开源,但由于工作太忙,业余时间不足,没有在进行完善,到了6月份由于工作原因、频繁设计和更改数据库、经常使用自己写的此插件、节省了很多时间,解决了很多问题 ,在仅有且不多的业余时间中、进行开源准备,于2020年6月22日,开源,欢迎大家使用、建议、并贡献。
  关于名字,想一个太难了,好在我这个聪明的小脑瓜灵感一现,怎么突出它的小,但重要呢?从小就学过雷锋的螺丝钉精神,摘自雷锋日记:虽然是细小的螺丝钉,是个细微的小齿轮,然而如果缺了它,那整个的机器就无法运转了,慢说是缺了它,即使是一枚小螺丝钉没拧紧,一个小齿轮略有破损,也要使机器的运转发生故障的...,感觉自己写的这个工具,很有这意味,虽然很小、但是开发中缺了它还不行,于是便起名为screw(螺丝钉)。
maven依赖配置

    <dependency>
            <groupId>cn.smallbun.screw</groupId>
            screw-core</artifactId>
            <version>1.0.5</version>
            <exclusions>
                <exclusion>
                  <groupId>org.freemarker</groupId>
                  freemarker</artifactId>
                </exclusion>
                <exclusion>
                  <groupId>com.alibaba</groupId>
                  fastjson</artifactId>
                </exclusion>
            </exclusions>
      </dependency>
      <dependency>
            <groupId>org.apache.velocity</groupId>
            velocity-engine-core</artifactId>
            <version>2.3</version>
      </dependency>主代码部分
package com.heit.road.web.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.smallbun.screw.core.Configuration;
import cn.smallbun.screw.core.engine.EngineConfig;
import cn.smallbun.screw.core.engine.EngineFileType;
import cn.smallbun.screw.core.engine.EngineTemplateType;
import cn.smallbun.screw.core.execute.DocumentationExecute;
import cn.smallbun.screw.core.process.ProcessConfig;
import com.heit.road.service.util.ServletUtils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

@Tag(name = "管理后台 - 数据库文档")
@RestController
@RequestMapping("/infra/db-doc")
public class DatabaseDocController {

    @Resource
    private DataSource db; //获取项目数据源


    private static final String FILE_OUTPUT_DIR = System.getProperty("java.io.tmpdir") + File.separator
            + "db-doc";
    private static final String DOC_FILE_NAME = "数据库文档";
    private static final String DOC_VERSION = "1.0.0";
    private static final String DOC_DESCRIPTION = "文档描述";

    @GetMapping("/export-html")
    @Operation(summary = "导出 html 格式的数据文档")
    @Parameter(name = "deleteFile", description = "是否删除在服务器本地生成的数据库文档", example = "true")
    public void exportHtml(@RequestParam(defaultValue = "true") Boolean deleteFile,
                           HttpServletResponse response) throws IOException {
      doExportFile(EngineFileType.HTML, deleteFile, response);
    }

    @GetMapping("/export-word")
    @Operation(summary = "导出 word 格式的数据文档")
    @Parameter(name = "deleteFile", description = "是否删除在服务器本地生成的数据库文档", example = "true")
    public void exportWord(@RequestParam(defaultValue = "true") Boolean deleteFile,
                           HttpServletResponse response) throws IOException {
      doExportFile(EngineFileType.WORD, deleteFile, response);
    }

    @GetMapping("/export-markdown")
    @Operation(summary = "导出 markdown 格式的数据文档")
    @Parameter(name = "deleteFile", description = "是否删除在服务器本地生成的数据库文档", example = "true")
    public void exportMarkdown(@RequestParam(defaultValue = "true") Boolean deleteFile,
                               HttpServletResponse response) throws IOException {
      doExportFile(EngineFileType.MD, deleteFile, response);
    }

    private void doExportFile(EngineFileType fileOutputType, Boolean deleteFile,
                              HttpServletResponse response) throws IOException {
      String docFileName = DOC_FILE_NAME + "_" + IdUtil.fastSimpleUUID();
      String filePath = doExportFile(fileOutputType, docFileName);
      String downloadFileName = DOC_FILE_NAME + fileOutputType.getFileSuffix(); //下载后的文件名
      try {
            // 读取,返回
            ServletUtils.writeAttachment(response, downloadFileName, FileUtil.readBytes(filePath));
      } finally {
            handleDeleteFile(deleteFile, filePath);
      }
    }

    /**
   * 输出文件,返回文件路径
   *
   * @param fileOutputType 文件类型
   * @param fileName       文件名, 无需 ".docx" 等文件后缀
   * @return 生成的文件所在路径
   */
    private String doExportFile(EngineFileType fileOutputType, String fileName) {
      try (HikariDataSource dataSource = buildDataSource()) {
            // 创建 screw 的配置
            Configuration config = Configuration.builder()
                  .version(DOC_VERSION)// 版本
                  .description(DOC_DESCRIPTION) // 描述
                  .dataSource(dataSource) // 数据源
                  .engineConfig(buildEngineConfig(fileOutputType, fileName)) // 引擎配置
                  .produceConfig(buildProcessConfig()) // 处理配置
                  .build();

            // 执行 screw,生成数据库文档
            new DocumentationExecute(config).execute();

            return FILE_OUTPUT_DIR + File.separator + fileName + fileOutputType.getFileSuffix();
      }
    }

    private void handleDeleteFile(Boolean deleteFile, String filePath) {
      if (!deleteFile) {
            return;
      }
      FileUtil.del(filePath);
    }

    /**
   * 创建数据源
   */
    private HikariDataSource buildDataSource() {
      HikariConfig hikariConfig = new HikariConfig();
      hikariConfig.setJdbcUrl(((HikariDataSource) db).getJdbcUrl());
      hikariConfig.setUsername(((HikariDataSource) db).getUsername());
      hikariConfig.setPassword(((HikariDataSource) db).getPassword());
      hikariConfig.addDataSourceProperty("useInformationSchema", "true"); // 设置可以获取 tables remarks 信息
      // 创建数据源
      return new HikariDataSource(hikariConfig);
    }

    /**
   * 创建 screw 的引擎配置
   */
    private static EngineConfig buildEngineConfig(EngineFileType fileOutputType, String docFileName) {
      return EngineConfig.builder()
                .fileOutputDir(FILE_OUTPUT_DIR) // 生成文件路径
                .openOutputDir(false) // 打开目录
                .fileType(fileOutputType) // 文件类型
                .produceType(EngineTemplateType.velocity) // 文件类型
                .fileName(docFileName) // 自定义文件名称
                .build();
    }

    /**
   * 创建 screw 的处理配置,一般可忽略
   * 指定生成逻辑、当存在指定表、指定表前缀、指定表后缀时,将生成指定表,其余表不生成、并跳过忽略表配置
   */
    private static ProcessConfig buildProcessConfig() {
      return ProcessConfig.builder()
                .ignoreTablePrefix(Arrays.asList("QRTZ_", "ACT_")) // 忽略表前缀
                .build();
    }


工具类
package com.heit.road.service.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
* 客户端工具类
*
*/
public class ServletUtils {

    /**
   * 返回 JSON 字符串
   *
   * @param response 响应
   * @param object 对象,会序列化成 JSON 字符串
   */
    @SuppressWarnings("deprecation") // 必须使用 APPLICATION_JSON_UTF8_VALUE,否则会乱码
    public static void writeJSON(HttpServletResponse response, Object object) {
      String content = JsonUtils.toJsonString(object);
      ServletUtil.write(response, content, MediaType.APPLICATION_JSON_UTF8_VALUE);
    }

    /**
   * 返回附件
   *
   * @param response 响应
   * @param filename 文件名
   * @param content 附件内容
   * @throws IOException
   */
    public static void writeAttachment(HttpServletResponse response, String filename, byte[] content) throws IOException {
      // 设置 header 和 contentType
      response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
      response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
      // 输出附件
      IoUtil.write(response.getOutputStream(), false, content);
    }

    /**
   * @param request 请求
   * @return ua
   */
    public static String getUserAgent(HttpServletRequest request) {
      String ua = request.getHeader("User-Agent");
      return ua != null ? ua : "";
    }

    /**
   * 获得请求
   *
   * @return HttpServletRequest
   */
    public static HttpServletRequest getRequest() {
      RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
      if (!(requestAttributes instanceof ServletRequestAttributes)) {
            return null;
      }
      return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    public static String getUserAgent() {
      HttpServletRequest request = getRequest();
      if (request == null) {
            return null;
      }
      return getUserAgent(request);
    }

    public static String getClientIP() {
      HttpServletRequest request = getRequest();
      if (request == null) {
            return null;
      }
      return ServletUtil.getClientIP(request);
    }

    public static boolean isJsonRequest(ServletRequest request) {
      return StrUtil.startWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE);
    }



来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: 生成数据库的表结构文档