在企業級 Java 開發中,MyBatis 作為優秀的持久層框架,極大地簡化了 JDBC 操作。然而,面對數十甚至上百張資料表,手動編寫實體類、Mapper 接口及 XML 映射文件不僅繁瑣,還容易出錯。本文將詳細介紹如何結合 MyBatis Generator 與 Ant 腳本,在 Eclipse 環境下一鍵自動生成所有持久層代碼,大幅提升開發效率。
MyBatis Generator (MBG) 是官方提供的代碼生成工具,支援通過配置文件指定資料庫連線、目標包路徑、表映射規則等。預設情況下 MBG 以命令列方式運行,我們將其封裝為 Ant 任務,只需在 Eclipse 的 Ant 視圖中雙擊執行,即可完成全量代碼生成。
請從 MyBatis Generator 官方發布頁 下載對應版本的 mybatis-generator-core-x.x.x.jar,並放入專案 WebContent/WEB-INF/lib/ 目錄。
確保已導入對應資料庫的 JDBC 驅動(本文以 MySQL 為例,需 mysql-connector-java-5.1.x-bin.jar)。
建議採用標準 Maven 目錄約定,便於後續維護:
src/main/java — Java 源碼(實體類、Mapper 接口)src/main/resources — 資源文件(Mapper XML、配置文件)src/main/env/dev — 開發環境專屬配置(JDBC、緩存、日誌等)src/test/java — 測試代碼Eclipse 添加源文件夾方法: 右鍵專案 → Build Path → Configure Build Path → Source 頁籤 → Add Folder,勾選上述目錄。
在專案根目錄建立 generatorConfig.xml,關鍵配置說明如下:
<?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>
<!-- 資料庫驅動 JAR 路徑(相對專案根目錄) -->
<classPathEntry location="WebContent/WEB-INF/lib/mysql-connector-java-5.1.26-bin.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 註釋生成策略:抑制所有註釋與時間戳 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true" />
</commentGenerator>
<!-- 資料庫連線資訊(請根據實際環境修改) -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/your_db"
userId="root" password="root">
</jdbcConnection>
<!-- Java 類型解析策略:預設 false 允許自動映射 Long/Integer/Short -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 實體類生成配置 -->
<javaModelGenerator targetPackage="com.yourpkg.model" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- Mapper XML 生成配置 -->
<sqlMapGenerator targetPackage="sqlmaps" targetProject="src/main/resources">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- Mapper 接口生成配置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.yourpkg.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 表映射配置:每張表一組 -->
<table tableName="user" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
關鍵修改點: 請根據實際專案修改targetPackage、資料庫連線資訊、tableName及domainObjectName。若有多張表,在<context>內重複添加<table>節點。
同目錄下建立 build_mybatis.xml:
<project default="genfiles" basedir=".">
<property name="generated.source.dir" value="${basedir}" />
<path id="ant.run.lib.path">
<pathelement location="${basedir}/WebContent/WEB-INF/lib/mybatis-generator-core-1.3.2.jar"/>
</path>
<target name="genfiles" description="Generate MyBatis Artifacts">
<taskdef name="mbgenerator" classname="org.mybatis.generator.ant.GeneratorAntTask" classpathref="ant.run.lib.path"/>
<mbgenerator overwrite="true" configfile="generatorConfig.xml" verbose="false">
<propertyset>
<propertyref name="generated.source.dir" />
</propertyset>
</mbgenerator>
</target>
</project>
注意: pathelement 路徑需與實際 JAR 文件名一致;configfile 指向上一步的配置文件。
build_mybatis.xml 拖入視圖genfiles 執行BUILD SUCCESSFUL 即成功CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(32) DEFAULT NULL, `password` varchar(64) DEFAULT NULL, `email` varchar(64) DEFAULT NULL, `birthday` date DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
classPathEntry 路徑與驅動 JAR 版本是否匹配targetProject 路徑存在mybatis-generator-core JAR 版本與 taskdef 的 classname 對應通過 MyBatis Generator + Ant 腳本,我們將重複性的持久層代碼編寫轉化為一鍵自動化流程,不僅消除了手工錯誤,更讓團隊專注於業務邏輯開發。配置文件一經完善,新增資料表只需在 <table> 節點追加配置並重新執行即可,極大提升了專案的可維護性與擴展性。