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方式進行代碼生成,因爲集成和使用比較簡單。

<!--more-->

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”說明生成已經成功了,如果出現錯誤,根據錯誤提示信息排除處理錯誤即可。

MyBatis Generator 示例源碼:https://github.com/vipstone/s...

三、安裝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”插件,可以很方便的幫我們開發和調試代碼,真是實實在在的福利。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章