1. 程式人生 > >Spring Boot (七)MyBatis程式碼自動生成和輔助外掛

Spring Boot (七)MyBatis程式碼自動生成和輔助外掛

一、簡介

1.1 MyBatis Generator介紹

MyBatis Generator 是MyBatis 官方出品的一款,用來自動生成MyBatis的 mapper、dao、entity 的框架,讓我們省去規律性最強的一部分最基礎的程式碼編寫。

1.2 MyBatis Generator使用

MyBatis Generator的使用方式有4種:

  • 命令列生成
  • Maven方式生成
  • 使用Ant任務生成
  • 使用Java程式碼生成

其中推薦使用Maven方式進行程式碼生成,因為整合和使用比較簡單。

1.3 開發環境

MySQL:8.0.12

MyBatis Generator:1.3.7

Maven:4.0

IDEA:2018.2

二、程式碼自動生成配置

上面介紹了使用MyBatis Generator的幾種方式,其中最推薦使用的是Maven方式,所以下面我們來看Maven方式的MyBatis程式碼生成,分為四步:

Step1:新增依賴

配置pom.xml檔案,增加依賴和配置生成檔案(“generatorConfig.xml”)路徑:

<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.7</version>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>
    </dependencies>
    <executions>
        <execution>
            <id>Generate MyBatis Artifacts</id>
            <phase>package</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <!--允許移動生成的檔案 -->
        <verbose>true</verbose>
        <!-- 是否覆蓋 -->
        <overwrite>true</overwrite>
        <!-- 自動生成的配置 -->
        <configurationFile>generatorConfig.xml</configurationFile>
    </configuration>
</plugin>

Step2:新增配置檔案

根據上面在pom裡的配置,我們需要新增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"/>

    <!--defaultModelType="flat" 大資料欄位,不分表 -->
    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="autoDelimitKeywords" value="true" />
        <property name="beginningDelimiter" value="`" />
        <property name="endingDelimiter" value="`" />
        <property name="javaFileEncoding" value="utf-8" />
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />

        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />

        <!-- 註釋 -->
        <commentGenerator >
            <property name="suppressAllComments" value="true"/><!-- 是否取消註釋 -->
            <property name="suppressDate" value="true" /> <!-- 是否生成註釋代時間戳-->
        </commentGenerator>
        
        <!--資料庫連結地址賬號密碼-->
        <jdbcConnection driverClass="${spring.datasource.driver-class-name}"
                        connectionURL="${spring.datasource.url}"
                        userId="${spring.datasource.username}"
                        password="${spring.datasource.password}">
        </jdbcConnection>
        
        <!-- 型別轉換 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自動轉化以下型別(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!--生成Model類存放位置-->
        <javaModelGenerator targetPackage="com.hello.springboot.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 生成mapxml檔案 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources/mybatis" >
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- 生成mapxml對應client,也就是介面dao -->
        <javaClientGenerator targetPackage="com.hello.springboot.dao" targetProject="src/main/java" type="XMLMAPPER" >
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <table tableName="article" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
            <generatedKey column="id" sqlStatement="Mysql" identity="true" />
        </table>

        <table tableName="user_log" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
            <generatedKey column="id" sqlStatement="Mysql" identity="true" />
        </table>

    </context>
</generatorConfiguration>

其中資料庫連線的配置,是從application.properties直接讀取的。

Step3:配置全域性屬性檔案

全域性屬性檔案application.properties的配置,和Spring Boot增加MyBatis的配置是一樣的,如果你的Spring Boot專案裡面已經配置了MyBatis支援,請忽略此步驟。

# MyBatis 配置
spring.datasource.url=jdbc:mysql://172.16.10.79:3306/mytestdb?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.type-aliases-package=com.hello.springboot.mapper
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

注意: MySQL 6以後JDBC的配置就不一樣了,參照如上MySQL 8的配置。

Step4:點選Maven生成程式碼

如果你使用的是IDEA,點選最右側的Maven Projects => 點選mybatis-generator => 右鍵mybatis-generator:generate => Run Maven Build,如下圖所示:

正常控制檯輸出“BUILD SUCCESS”說明生成已經成功了,如果出現錯誤,根據錯誤提示資訊排除處理錯誤即可。

三、安裝IDEA外掛

如果你使用的是 IDEA,那麼強烈建議你安裝一款免費的IDEA外掛“Free MyBatis plugin”,可以實現dao到mapper xml對應方法的快速對映,點選任意一個快速調整到相應的方法,提高工作效率,效果如下圖所示:

點選綠色的箭頭直接跳轉到了mapper xml對應的方法了,如下圖所示:

可以相互點選,進行對應的跳轉。

安裝步驟

  • 點選選單欄Flie => Settings
  • 點選Browse repostitories..
  • 輸入“Free MyBatis plugin”查詢外掛
  • 點選安裝,重啟IDEA

關鍵步驟的截圖如下:

四、總結

使用了MyBatis Generator可以幫我們自動生成實體類,和5個最基礎的方法,大大的提高我們的工作效率,使用者只需要按需寫自己獨有的一些業務即可。同時增加“Free MyBatis plugin”外掛,可以很方便的幫我們開發和除錯程式碼,真是實實在在的福利。