One-click generation of database documents, called Swagger in the database world

In projects, we often need to organize database table structure documents.

Under normal circumstances, we manually organize the database table structure documents, and when the table structure changes, we manually maintain it.

It’s fine when there are few database tables. After there are too many database tables, it’s not too much trouble to manually organize and maintain the database table structure documents, and it’s also very error-prone!

Are there any useful tools to help us automatically generate database table structure documents?

Of course there is! A friend on Github has open sourced an automatic generation tool for database table structure documents - screw .

Project address: https://github.com/pingfangushi/screw .

The translation of screw means screw. The author hopes that this tool can help our development work like a screw.

At present, screw already supports most of the common databases on the market, such as MySQL, MariaDB, Oracle, SqlServer, PostgreSQL, and TiDB.

In addition, screw is also very simple to use. According to the official website, you can successfully use it locally in less than 10 minutes!

Quick start

In order to verify the effect of screw automatically generating database table structure documents, we first create a simple database table for storing blog data.

CREATE TABLE `blog` (
  `id` bigint(20NOT NULL AUTO_INCREMENT COMMENT '主键',
  `title` varchar(255NOT NULL COMMENT '博客标题',
  `content` longtext NOT NULL COMMENT '博客内容',
  `description` varchar(255DEFAULT NULL COMMENT '博客简介',
  `cover` varchar(255DEFAULT NULL COMMENT '博客封面图片地址',
  `views` int(11NOT NULL DEFAULT '0' COMMENT '博客阅读次数',
  `user_id` bigint(20DEFAULT '0' COMMENT '发表博客的用户ID',
  `channel_id` bigint(20NOT NULL COMMENT '博客分类ID',
  `recommend` bit(1NOT NULL DEFAULT b'0' COMMENT '是否推荐',
  `top` bit(1NOT NULL DEFAULT b'0' COMMENT '是否置顶',
  `comment` bit(1NOT NULL DEFAULT b'1' COMMENT '是否开启评论',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`)
ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 COMMENT='博客';

Java based code

import dependencies

Create a normal Maven project and that's it! Then introduce the three dependencies of screw, HikariCP and MySQL.

<!--screw-->
<dependency>
    <groupId>cn.smallbun.screw</groupId>
    <artifactId>screw-core</artifactId>
    <version>1.0.5</version>
</dependency>
<!-- HikariCP -->
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>3.4.5</version>
</dependency>
<!--MySQL-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.20</version>
</dependency>

You can get the latest version of screw at mvnrepository at the following address.

https://mvnrepository.com/artifact/cn.smallbun.screw/screw-core

Write code

The entire code logic of the code to generate the database document is relatively simple, we only need to go through the following 5 steps:

// 1.获取数据源
DataSource dataSource = getDataSource();
// 2.获取数据库文档生成配置(文件路径、文件类型)
EngineConfig engineConfig = getEngineConfig();
// 3.获取数据库表的处理配置,可忽略
ProcessConfig processConfig = getProcessConfig();
// 4.Screw 完整配置
Configuration config = getScrewConfig(dataSource, engineConfig, processConfig);
// 5.执行生成数据库文档
new DocumentationExecute(config).execute();

1. Get the database source

Configure the database and database connection pool.Be sure to modify the database-related configuration to your own.

/**
 * 获取数据库源
 */

private static DataSource getDataSource() {
    //数据源
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
    hikariConfig.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/javaguide-blog");
    hikariConfig.setUsername("root");
    hikariConfig.setPassword("123456");
    //设置可以获取tables remarks信息
    hikariConfig.addDataSourceProperty("useInformationSchema""true");
    hikariConfig.setMinimumIdle(2);
    hikariConfig.setMaximumPoolSize(5);
    return new HikariDataSource(hikariConfig);
}

2. Get the file generation configuration

This step specifies where the database documentation will be generated, the file type, and the file name.

/**
 * 获取文件生成配置
 */

private static EngineConfig getEngineConfig() {
    //生成配置
    return EngineConfig.builder()
            //生成文件路径
            .fileOutputDir("/Users/guide/Documents/代码示例/screw-demo/doc")
            //打开目录
            .openOutputDir(true)
            //文件类型
            .fileType(EngineFileType.HTML)
            //生成模板实现
            .produceType(EngineTemplateType.freemarker)
            //自定义文件名称
            .fileName("数据库结构文档").build();
}

如果不配置生成文件路径的话,默认也会存放在项目的 doc 目录下。

另外,我们这里指定生成的文件格式为 HTML。除了 HTML 之外,screw 还支持 Word 、Markdown 这两种文件格式。

不太建议生成 Word 格式,比较推荐 Markdown 格式。

3、获取数据库表的处理配置

这一步你可以指定忽略生成哪些表。

/**
 * 获取数据库表的处理配置,可忽略
 */

private static ProcessConfig getProcessConfig() {
    return ProcessConfig.builder()
      // 指定只生成 blog 表
      .designatedTableName(new ArrayList<>(Collections.singletonList("blog")))
      .build();
}

还可以指定只生成哪些表。

private static ProcessConfig getProcessConfig() {
    ArrayList<String> ignoreTableName = new ArrayList<>();
    ignoreTableName.add("test_user");
    ignoreTableName.add("test_group");
    ArrayList<String> ignorePrefix = new ArrayList<>();
    ignorePrefix.add("test_");
    ArrayList<String> ignoreSuffix = new ArrayList<>();
    ignoreSuffix.add("_test");
    return ProcessConfig.builder()
            //忽略表名
            .ignoreTableName(ignoreTableName)
            //忽略表前缀
            .ignoreTablePrefix(ignorePrefix)
            //忽略表后缀
            .ignoreTableSuffix(ignoreSuffix)
            .build();
}

这一步也可以省略。如果不指定 ProcessConfig 的话,就会按照默认配置来!

4、生成 screw 完整配置

根据前面 3 步,生成 screw 完整配置。

private static Configuration getScrewConfig(DataSource dataSource, EngineConfig engineConfig, ProcessConfig processConfig) {
    return Configuration.builder()
            //版本
            .version("1.0.0")
            //描述
            .description("数据库设计文档生成")
            //数据源
            .dataSource(dataSource)
            //生成配置
            .engineConfig(engineConfig)
            //生成配置
            .produceConfig(processConfig)
            .build();
}

5、执行生成数据库文档

下图就是生成的 HTML 格式的数据库设计文档。

基于 Maven 插件

除了基于 Java 代码这种方式之外,你还可以通过 screw 提供的 Maven 插件来生成数据库文档。方法也非常简单!

1、配置 Maven 插件

务必将数据库相关的配置修改成你自己的。

<build>
    <plugins>
        <plugin>
            <groupId>cn.smallbun.screw</groupId>
            <artifactId>screw-maven-plugin</artifactId>
            <version>1.0.5</version>
            <dependencies>
                <!-- HikariCP -->
                <dependency>
                    <groupId>com.zaxxer</groupId>
                    <artifactId>HikariCP</artifactId>
                    <version>3.4.5</version>
                </dependency>
                <!--mysql driver-->
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.20</version>
                </dependency>
            </dependencies>
            <configuration>
                <!--username-->
                <username>root</username>
                <!--password-->
                <password>123456</password>
                <!--driver-->
                <driverClassName>com.mysql.cj.jdbc.Driver</driverClassName>
                <!--jdbc url-->
                <jdbcUrl>jdbc:mysql://127.0.0.1:3306/javaguide-blog</jdbcUrl>
                <!--生成文件类型-->
                <fileType>MD</fileType>
                <!--打开文件输出目录-->
                <openOutputDir>true</openOutputDir>
                <!--生成模板-->
                <produceType>freemarker</produceType>
                <!--文档名称 为空时:将采用[数据库名称-描述-版本号]作为文档名称-->
                <fileName>数据库结构文档</fileName>
                <!--描述-->
                <description>数据库设计文档生成</description>
                <!--版本-->
                <version>${project.version}</version>
                <!--标题-->
                <title>数据库文档</title>
            </configuration>
            <executions>
                <execution>
                    <phase>compile</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

2、手动执行生成数据库文档

我们这里指定生成的是 Markdown 格式。

下图就是生成的 Markdown 格式的数据库设计文档,效果还是非常不错的!



本文分享自微信公众号 - 武培轩(wupeixuan404)。
如有侵权,请联系 [email protected] 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324163082&siteId=291194637