在 Maven 項目中,可以通過集成 數據庫文檔生成工具(如 screw-maven-plugin
、mybatis-generator
或 liquibase
)來自動生成數據庫文檔。以下是使用 screw-maven-plugin
(推薦)的完整配置步驟:
1. 添加插件配置到 pom.xml
將以下配置添加到 <build>
→ <plugins>
部分:
<build><plugins><!-- 數據庫文檔生成插件 --><plugin><groupId>cn.smallbun.screw</groupId><artifactId>screw-maven-plugin</artifactId><version>1.0.5</version><dependencies><!-- 數據庫驅動(以MySQL為例) --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.32</version></dependency><!-- HikariCP連接池 --><dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId><version>3.4.5</version></dependency></dependencies><configuration><!-- 數據庫連接配置 --><username>${db.username}</username><password>${db.password}</password><jdbcUrl>jdbc:mysql://${db.host}:${db.port}/${db.name}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false</jdbcUrl><driverClassName>com.mysql.cj.jdbc.Driver</driverClassName><!-- 文檔生成配置 --><fileType>HTML</fileType> <!-- 可選:HTML | WORD | MD --><fileName>數據庫文檔</fileName><title>項目數據庫設計</title><description>自動生成的數據庫文檔</description><version>${project.version}</version><openOutputDir>true</openOutputDir> <!-- 生成后是否打開目錄 --><!-- 忽略表(可選) --><ignoreTablePrefix>temp_,test_</ignoreTablePrefix></configuration><executions><execution><phase>compile</phase> <!-- 綁定到編譯階段 --><goals><goal>run</goal></goals></execution></executions></plugin></plugins>
</build>
2. 配置數據庫信息
在 pom.xml
或 settings.xml
中定義數據庫變量(避免明文密碼):
方式一:在 pom.xml
的 <properties>
中配置
<properties><db.host>localhost</db.host><db.port>3306</db.port><db.name>your_database</db.name><db.username>root</db.username><db.password>123456</db.password>
</properties>
方式二:在 settings.xml
中配置(更安全)
<settings><profiles><profile><id>db-config</id><properties><db.password>ENC(加密后的密碼)</db.password></properties></profile></profiles><activeProfiles><activeProfile>db-config</activeProfile></activeProfiles>
</settings>
3. 執行生成命令
運行以下 Maven 命令生成文檔:
mvn compile # 插件綁定到compile階段,會自動觸發
# 或單獨執行插件
mvn screw:run
生成的文檔默認輸出到:
target/doc/數據庫文檔.{html|md|docx}
5. 高級配置選項
參數 | 說明 |
---|---|
fileType | 輸出格式:HTML (默認)、WORD 、MD |
ignoreTablePrefix | 忽略表前綴(如 test_ ) |
produceType | 模板引擎:freemarker (默認)或 velocity |
design | 自定義描述信息(支持HTML標簽) |
6. 注意事項
- 數據庫兼容性
- 支持 MySQL/Oracle/PostgreSQL/SQL Server 等主流數據庫(需正確配置驅動)。
- 密碼安全
- 生產環境建議使用 Maven 密碼加密(官方指南)。
- 多模塊項目
- 在父 POM 中配置插件,子模塊通過
<inherited>true</inherited>
繼承。
- 在父 POM 中配置插件,子模塊通過
替代方案對比
工具 | 優點 | 缺點 |
---|---|---|
screw-maven-plugin | 輕量、支持多格式、中文友好 | 僅生成文檔,無數據庫變更管理 |
mybatis-generator | 可生成代碼+文檔 | 配置復雜,文檔功能較弱 |
liquibase | 支持數據庫版本管理 | 文檔生成需額外插件 |
推薦選擇 screw-maven-plugin
快速生成簡潔的數據庫文檔!