MyBatis Generator (MBG) 是官方代碼生成工具,能根據資料庫表結構自動生成 Entity、Mapper XML、DAO 介面,大幅減少樣板代碼編寫。本文詳細解析 generator.xml 配置、Table 標籤屬性、生成命令與常見坑點。
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "https://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- JDBC 驅動 JAR 路徑 -->
<classPathEntry location="F:\xy\jars\mysql-connector-java-5.0.7-bin.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 禁止生成註釋 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 資料庫連線 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/db_MybatisTest"
userId="root" password="mysqltest">
</jdbcConnection>
<!-- 類型解析策略 -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- Entity 生成位置 -->
<javaModelGenerator targetPackage="com.xy.model" targetProject="F:\xy\mybatis-generator\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- Mapper XML 生成位置 -->
<sqlMapGenerator targetPackage="com.xy.mapping" targetProject="F:\xy\mybatis-generator\src">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- DAO 介面生成位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.xy.dao" targetProject="F:\xy\mybatis-generator\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 表映射配置 -->
<table tableName="t_student" domainObjectName="Student"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
<ignoreColumn column="name" />
</table>
</context>
</generatorConfiguration>
| 屬性 | 說明 |
|---|---|
| tableName | 資料庫實際表名 |
| domainObjectName | 生成的 Entity 類名 |
| enableCountByExample 等 | 設為 false 可避免生成 Example 類,減少冗餘代碼 |
<ignoreColumn column="name" />:忽略特定欄位不生成屬性<columnOverride column="FIELD" jdbcType="VARCHAR" />:強制指定欄位對應 Java 類型java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
參數說明:-overwrite 覆蓋已存在文件;需確保 JAR 包與配置文件路徑正確。
mybatis-generator-core-x.x.x.jar + 資料庫驅動 JAR<context> 下配置多個 <table> 標籤CommentGenerator 介面替換預設註釋生成邏輯mybatis-generator-maven-plugin 在建置過程中自動生成掌握 MBG 能讓您專注於業務邏輯開發,將重複的 CRUD 代碼交給工具自動化處理。