MyBatis Generator生成程式碼的幾種方式
由於MyBatis屬於一種半自動的ORM框架,所以主要的工作就是配置Mapping對映檔案,但是由於手寫對映檔案很容易出錯,所以可利用MyBatis生成器自動生成實體類、DAO介面和Mapper對映檔案。這樣可以省去一部分的功夫,下面將介紹幾種生成方式:
MyBatis Generator 參考文件:
第一種:使用命令列建立
生成程式碼需要的檔案和jar包:
其中有mybatis框架的jar包,資料庫驅動程式jar包以及MyBatis生成器jar包。其中的generatorConfig.xml是需要我們來配置的檔案,配置如下:
當以上這些完成之後,只需要開啟控制檯,進入lib目錄下,執行指令碼:java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite即可。<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 資料庫驅動--> <classPathEntry location="mysql-connector-java-5.1.7-bin.jar"/> <!-- jdbc.driver=com.mysql.jdbc.Driver url=jdbc:mysql:///test username=root password=123456 --> <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:///test" userId="root" password="123456"> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 修改包名字 --> <javaModelGenerator targetPackage="com.solin.entity" targetProject="../src"> <property name="enableSubPackages" value="false" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <sqlMapGenerator targetPackage="com.solin.mapper" targetProject="../src"> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="com.solin.mapper" targetProject="../src"> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 要生成的表 tableName是資料庫中的表名或檢視名 domainObjectName是實體類名--> <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration>
這樣在生成之後,就可以在src目錄下找到相應的資料夾,每張表都會對應三個檔案(實體類、介面、配置檔案)。
第二種:通過MybatisGenerator類和配置檔案生成程式碼
專案結構如下:
generatorConfig.xml配置如下:
建立MybatisGeneratorUtil類:<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 資料庫驅動--> <classPathEntry location="/"/> <!-- jdbc.driver=com.mysql.jdbc.Driver url=jdbc:mysql:///test username=root password=123456 --> <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:///test" userId="root" password="123456"> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 修改包名字 --> <javaModelGenerator targetPackage="com.solin.entity" targetProject=".\src"> <property name="enableSubPackages" value="false" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <sqlMapGenerator targetPackage="com.solin.mapper" targetProject=".\src"> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="com.solin.mapper" targetProject=".\src"> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 要生成的表 tableName是資料庫中的表名或檢視名 domainObjectName是實體類名--> <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration>
執行main方法就可以生成程式碼了,執行後的結果如下:package com.solin; import java.io.File; import java.util.ArrayList; import java.util.List; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; public class MybatisGeneratorUtil { public static void main(String[] args) throws Exception { generator(); } private static void generator() throws Exception { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("generatorConfig.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); System.out.println("程式碼生成完畢>>>>>>>>>>>>"); } }
第三種方式 通過GeneratorAntTask類和配置檔案生成
專案結構如下:
generatorConfig.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 資料庫驅動-->
<classPathEntry location="/"/>
<!--
jdbc.driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
username=root
password=root
-->
<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:///test"
userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 修改包名字 -->
<javaModelGenerator targetPackage="com.solin.entity" targetProject=".\src">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.solin.mapper" targetProject=".\src">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.solin.mapper" targetProject=".\src">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 要生成的表 tableName是資料庫中的表名或檢視名 domainObjectName是實體類名-->
<table tableName="user"
domainObjectName="User"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
建立GeneratorAntTaskUtil類:
package com.solin;
import org.mybatis.generator.ant.GeneratorAntTask;
public class GeneratorAntTaskUtil {
public static void main(String[] args) throws Exception {
generator();
}
private static void generator() throws Exception {
GeneratorAntTask task = new GeneratorAntTask();
task.setConfigfile("generatorConfig.xml"); //(配置檔案具體path)
task.execute();
System.out.println("程式碼生成完畢>>>>>>>>>>>>");
}
}
執行main方法就可以生成程式碼了,執行後的結果如下:
第四種:基於Maven外掛的方式
首先建立一個Maven工程,專案目錄如下:
pom.xml檔案配置如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.solin</groupId>
<artifactId>autoGenerate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>autoGenerate</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>autoGenerate</finalName>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<execution>
<id>Generate MyBatis Files</id>
<goals>
<goal>generate</goal>
</goals>
<phase>generate</phase>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
generatorConfig.xml檔案配置如下:<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 引入配置檔案 -->
<properties resource="application.properties"/>
<!-- 一個數據庫一個context -->
<context id="MBG" targetRuntime="MyBatis3">
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" />
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin" />
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin>
<!-- 註釋 -->
<commentGenerator >
<property name="suppressAllComments" value="true"/><!-- 是否取消註釋 -->
<property name="suppressDate" value="true" /> <!-- 是否生成註釋帶時間戳-->
</commentGenerator>
<!-- jdbc連線 -->
<jdbcConnection
driverClass="${jdbc.driverClassName}"
connectionURL="${jdbc.url}"
userId="${jdbc.username}"
password="${jdbc.password}">
</jdbcConnection>
<!-- 型別轉換 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自動轉化以下型別(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成實體類地址 -->
<javaModelGenerator targetPackage="${package.entity}" targetProject="src/main/java">
<!-- 該屬性只對MyBatis3有效,如果true就會使用構造方法入參,如果false就會使用setter方式。預設為false。 -->
<property name="constructorBased" value="true" />
<!-- 是否在當前路徑下新加一層schema,eg:fase路徑cn.ffcs.test.domain", true:cn.ffcs.test.domain".[schemaName] -->
<property name="enableSubPackages" value="false" />
<!-- 是否針對string型別的欄位在set的時候進行trim呼叫 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成mapxml檔案 -->
<sqlMapGenerator targetPackage="${package.mapper}" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成mapxml對應client,也就是介面dao -->
<javaClientGenerator type="XMLMAPPER" targetPackage="${package.mapper}" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 選擇一個table來生成相關檔案,可以有一個或多個table,必須要有table元素
選擇的table會生成一下檔案:
1,SQL map檔案
2,生成一個主鍵類;
3,除了BLOB和主鍵的其他欄位的類;
4,包含BLOB的類;
5,一個使用者生成動態查詢的條件類(selectByExample, deleteByExample),可選;
6,Mapper介面(可選)
tableName(必要):要生成物件的表名;
注意:大小寫敏感問題。正常情況下,MBG會自動的去識別資料庫識別符號的大小寫敏感度,在一般情況下,MBG會
根據設定的schema,catalog或tablename去查詢資料表,按照下面的流程:
1,如果schema,catalog或tablename中有空格,那麼設定的是什麼格式,就精確的使用指定的大小寫格式去查詢;
2,否則,如果資料庫的識別符號使用大寫的,那麼MBG自動把表名變成大寫再查詢;
3,否則,如果資料庫的識別符號使用小寫的,那麼MBG自動把表名變成小寫再查詢;
4,否則,使用指定的大小寫格式查詢;
另外的,如果在建立表的時候,使用的""把資料庫物件規定大小寫,就算資料庫識別符號是使用的大寫,在這種情況下也會使用給定的大小寫來建立表名;
這個時候,請設定delimitIdentifiers="true"即可保留大小寫格式;
可選:
1,schema:資料庫的schema;
2,catalog:資料庫的catalog;
3,alias:為資料表設定的別名,如果設定了alias,那麼生成的所有的SELECT SQL語句中,列名會變成:alias_actualColumnName
4,domainObjectName:生成的domain類的名字,如果不設定,直接使用表名作為domain類的名字;可以設定為somepck.domainName,那麼會自動把domainName類再放到somepck包裡面;
5,enableInsert(預設true):指定是否生成insert語句;
6,enableSelectByPrimaryKey(預設true):指定是否生成按照主鍵查詢物件的語句(就是getById或get);
7,enableSelectByExample(預設true):MyBatis3Simple為false,指定是否生成動態查詢語句;
8,enableUpdateByPrimaryKey(預設true):指定是否生成按照主鍵修改物件的語句(即update);
9,enableDeleteByPrimaryKey(預設true):指定是否生成按照主鍵刪除物件的語句(即delete);
10,enableDeleteByExample(預設true):MyBatis3Simple為false,指定是否生成動態刪除語句;
11,enableCountByExample(預設true):MyBatis3Simple為false,指定是否生成動態查詢總條數語句(用於分頁的總條數查詢);
12,enableUpdateByExample(預設true):MyBatis3Simple為false,指定是否生成動態修改語句(只修改物件中不為空的屬性);
13,modelType:參考context元素的defaultModelType,相當於覆蓋;
14,delimitIdentifiers:參考tableName的解釋,注意,預設的delimitIdentifiers是雙引號,如果類似MYSQL這樣的資料庫,使用的是`(反引號,那麼還需要設定context的beginningDelimiter和endingDelimiter屬性)
15,delimitAllColumns:設定是否所有生成的SQL中的列名都使用識別符號引起來。預設為false,delimitIdentifiers參考context的屬性
注意,table裡面很多引數都是對javaModelGenerator,context等元素的預設屬性的一個複寫;
-->
<table tableName="${tableName}"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
<!-- 參考 javaModelGenerator 的 constructorBased屬性-->
<property name="constructorBased" value="true" />
<!-- 如果設定為true,生成的model類會直接使用column本身的名字,而不會再使用駝峰命名方法,比如BORN_DATE,生成的屬性名字就是BORN_DATE,而不會是bornDate -->
<property name="useActualColumnNames" value="false" />
<!-- 預設為false,如果設定為true,在生成的SQL中,table名字不會加上catalog或schema; -->
<property name="ignoreQualifiersAtRuntime" value="false" />
<!-- 參考 javaModelGenerator 的 immutable 屬性 -->
<!-- <property name="immutable" value="false"/> -->
</table>
</context>
</generatorConfiguration>
對於generatorConfig.xml檔案中引入的application.properties檔案,裡面主要是資料庫連線資訊和生成的檔案的目錄資訊,application.properties檔案配置如下:jdbc.url=jdbc:mysql:///test?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root
package.entity=com.solin.autoGenerate.entity
package.mapper=com.solin.autoGenerate.mapper
#指定要生成程式碼的表名,如果tableName等於%,則生成全部表的程式碼
tableName=user
以上檔案配置好了之後,在專案上點選右鍵,如圖:在點選Run Configurations以後,會彈出對話方塊,在對話方塊上找到Maven Build,然後右鍵並且點選new,如下圖:
在新出現的介面上填寫Name,Base directory,Goals這三個地方,其中Name可以隨便寫,Base directory是你的工程的路徑,Goals這個地方不用變,照著圖寫,這個是maven外掛的命令。至於Maven Runtime下拉框可以不選,也可以選擇自己安裝在eclipse外面的那個。
點選Apply,在點選 Run,稍等一會,你可以看到generate執行成功了,如圖:
重新整理專案,可以看到生成的檔案,如圖:
第五種:通過eclipse mybatis generater程式碼生成外掛自動生成程式碼