MyBatis 逆向工程可依據資料庫結構自動生成實體類、Mapper 介面、XML 映射檔,大幅加速開發。本文以 mybatis-generator-core-1.3.2.jar 搭配 MySQL 為例,示範完整設定與執行步驟。
mybatis-generator-core-1.3.2.jarmysql-connector-java-5.1.13-bin.jar(或對應版本)project-root/
├── mybatis-generator-core-1.3.2.jar
├── mysql-connector-java-5.1.13-bin.jar
├── generatorConfig.xml
├── run.bat
└── src/ (輸出目錄,預先建立空資料夾)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"https://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- JDBC 驅動位置 -->
<classPathEntry location="mysql-connector-java-5.1.13-bin.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 資料庫連線 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/your_db"
userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 實體類輸出 -->
<javaModelGenerator targetPackage="com.example.model" targetProject="src">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- XML 映射檔輸出 -->
<sqlMapGenerator targetPackage="com.example.mapping" targetProject="src">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- Mapper 介面輸出 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.example.mapping" targetProject="src">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 指定要生成的表 -->
<table tableName="user" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
<!-- 若要全部表,tableName="%" 並移除 domainObjectName -->
</context>
</generatorConfiguration>
java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite
pause
run.bat 執行src/ 目錄下是否生成對應套件結構與檔案?useUnicode=true&characterEncoding=UTF-8 避免中文亂碼<context> 內重複 <table> 元素,或使用 tableName="%" 一次生成所有表(需移除 domainObjectName)mybatis-generator-maven-plugin 整合至建置流程,避免手動執行MyBatis Generator 讓「資料庫優先」開發模式落地更輕鬆,配置一次即可重複使用。掌握 generatorConfig.xml 關鍵節點設定,即可依專案需求彈性產出代碼,搭配 Maven Plugin 更能納入 CI/CD 流程。