1、核心文件generator.xmljava
指定數據庫jar包位置、數據庫鏈接信息、生成包的位置、表名等關鍵信息。該文件放在任意位置。mysql
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">sql
<generatorConfiguration>數據庫
<!-- 數據庫的JDBC驅動的jar包地址 -->mybatis
<classPathEntry location="F:\xy\jars\mysql-connector-java-5.0.7-bin.jar" />app
<context id="DB2Tables" targetRuntime="MyBatis3">dom
<!-- 是否去除自動生成的註釋 -->ide
<commentGenerator>編碼
<property name="suppressAllComments" value="true" />spa
</commentGenerator>
<!-- 數據庫鏈接的信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/db_MybatisTest"
userId="root" password="mysqltest">
</jdbcConnection>
<!-- false:JDBC DECIMAL、NUMERIC類型解析爲Integer,默認方式 -->
<!-- true: JDBC DECIMAL、NUMERIC類型解析爲java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成模型的包名和位置 -->
<javaModelGenerator targetPackage="com.xy.model" targetProject="F:\xy\mybatis-generator\src">
<!-- 是否讓schema做爲包的後綴 -->
<property name="enableSubPackages" value="true" />
<!-- 從數據庫返回的值被清理先後的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成映射文件的包名和位置 -->
<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>
<!-- tableName:數據庫表 -->
<!-- domainObjectName:對應於數據庫表的javaBean類名 -->
<table tableName="t_student" domainObjectName="Student" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
<!-- 忽略該字段(可省略) -->
<ignoreColumn column="name" />
</table>
</context>
</generatorConfiguration>
2、table標籤解析
①屬性
schema即爲數據庫名,tableName爲對應的數據庫表,domainObjectName是要生成的實體類。
若要生成例子可將enableCountByExample等設爲true, 就會生成一個對應domainObjectName的Example類,false則不生成,默認策略是true。
相似的還有enableUpdateByExample、enableDeleteByExample、enableSelectByExample、selectByExampleQueryId屬性。
②子標籤
若要對某些數據庫字段進行操做,能夠在table標籤中加入以下標籤
一、忽略某個字段
<ignoreColumn column="name" />
二、不管數據庫字段是何類型,生成的類屬性都是varchar
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
3、生成
mybatis-generator-core-1.3.2.jar是核心jar包,可在網上自行下載。命令窗口執行語句,執行成功後就會在generator.xml文件中指定的位置找到代碼了。
java -jar F:\xy\jars\mybatis-generator-core-1.3.2.jar -configfile F:\xy\generator.xml -overwrite
4、總結
使用Mybatis Generator須要
①兩個jar包——mybatis-generator-core-1.3.2.jar和數據庫jar包
②一個配置文件generator.xml
③執行語句
5、注意事項
①generator.xml格式:必須是以UTF-8無BOM格式編碼,用notepad++轉換。
②注意數據庫包的可用性,無效的數據庫包轉換會報錯。