Mybatis代碼生成器Mybatis-Generator使用詳解

Throwable : Mybatis代碼生成器Mybatis-Generator使用詳解

前提

最近在做創(chuàng)業(yè)項(xiàng)目的時(shí)候因?yàn)橛斜容^多的新需求示罗,需要頻繁基于DDL生成Mybatis適合的實(shí)體绰精、Mapper接口和映射文件及志。其中淡喜,代碼生成器是MyBatis Generator(MBG)卒密,用到了Mybatis-Generator-Core相關(guān)依賴(lài),這里通過(guò)一篇文章詳細(xì)地分析這個(gè)代碼生成器的使用方式缅糟。本文編寫(xiě)的時(shí)候使用的Mybatis-Generator版本為1.4.0,其他版本沒(méi)有進(jìn)行過(guò)調(diào)研扎筒。

引入插件

Mybatis-Generator的運(yùn)行方式有很多種:

  • 基于mybatis-generator-core-x.x.x.jar和其XML配置文件,通過(guò)命令行運(yùn)行酬姆。
  • 通過(guò)AntTask結(jié)合其XML配置文件運(yùn)行嗜桌。
  • 通過(guò)Maven插件運(yùn)行。
  • 通過(guò)Java代碼和其XML配置文件運(yùn)行轴踱。
  • 通過(guò)Java代碼和編程式配置運(yùn)行症脂。
  • 通過(guò)Eclipse Feature運(yùn)行谚赎。

這里只介紹通過(guò)Maven插件運(yùn)行和通過(guò)Java代碼和其XML配置文件運(yùn)行這兩種方式淫僻,兩種方式有個(gè)特點(diǎn):都要提前編寫(xiě)好XML配置文件诱篷。個(gè)人感覺(jué)XML配置文件相對(duì)直觀,后文會(huì)花大量篇幅去說(shuō)明XML配置文件中的配置項(xiàng)及其作用雳灵。這里先注意一點(diǎn):默認(rèn)的配置文件為ClassPath:generatorConfig.xml棕所。

通過(guò)編碼和配置文件運(yùn)行

通過(guò)編碼方式去運(yùn)行插件先需要引入mybatis-generator-core依賴(lài),編寫(xiě)本文的時(shí)候最新的版本為:

<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.4.0</version>
</dependency>

假設(shè)編寫(xiě)好的XML配置文件是ClassPath下的generator-configuration.xml悯辙,那么使用代碼生成器的編碼方式大致如下:

List<String> warnings = new ArrayList<>();
// 如果已經(jīng)存在生成過(guò)的文件是否進(jìn)行覆蓋
boolean overwrite = true;
File configFile = new File("ClassPath路徑/generator-configuration.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator generator = new MyBatisGenerator(config, callback, warnings);
generator.generate(null);

通過(guò)Maven插件運(yùn)行

如果使用Maven插件琳省,那么不需要引入mybatis-generator-core依賴(lài),只需要引入一個(gè)Maven的插件mybatis-generator-maven-plugin

<plugins>
    <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.4.0</version>
        <executions>
            <execution>
                <id>Generate MyBatis Artifacts</id>
                <goals>
                    <goal>generate</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <!-- 輸出詳細(xì)信息 -->
            <verbose>true</verbose>
            <!-- 覆蓋生成文件 -->
            <overwrite>true</overwrite>
            <!-- 定義配置文件 -->
            <configurationFile>${basedir}/src/main/resources/generator-configuration.xml</configurationFile>
        </configuration>
    </plugin>
</plugins>

mybatis-generator-maven-plugin的更詳細(xì)配置和可選參數(shù)可以參考:Running With Maven躲撰。插件配置完畢之后针贬,使用下面的命令即可運(yùn)行:

mvn mybatis-generator:generate

XML配置文件詳解

XML配置文件才是Mybatis-Generator的核心,它用于控制代碼生成的所有行為拢蛋。所有非標(biāo)簽獨(dú)有的公共配置的Key可以在mybatis-generator-corePropertyRegistry類(lèi)中找到桦他。下面是一個(gè)相對(duì)完整的配置文件的模板:

<?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="db.properties"/>

  <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />

  <context id="DB2Tables" targetRuntime="MyBatis3">

    <jdbcConnection driverClass="COM.ibm.db2.jdbc.app.DB2Driver"
        connectionURL="jdbc:db2:TEST"
        userId="db2admin"
        password="db2admin">
    </jdbcConnection>

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

    <commentGenerator>
        <property name="suppressDate" value="true"/>
        <property name="suppressAllComments" value="true"/>
    </commentGenerator>

    <javaTypeResolver>
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

    <javaModelGenerator targetPackage="test.model" targetProject="\MBGTestProject\src">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <sqlMapGenerator targetPackage="test.xml"  targetProject="\MBGTestProject\src">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

    <javaClientGenerator type="XMLMAPPER" targetPackage="test.dao"  targetProject="\MBGTestProject\src">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

    <table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" >
      <property name="useActualColumnNames" value="true"/>
      <generatedKey column="ID" sqlStatement="DB2" identity="true" />
      <columnOverride column="DATE_FIELD" property="startDate" />
      <ignoreColumn column="FRED" />
      <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
    </table>

  </context>
</generatorConfiguration>

配置文件中,最外層的標(biāo)簽為<generatorConfiguration>谆棱,它的子標(biāo)簽包括:

  • 0或者1個(gè)<properties>標(biāo)簽快压,用于指定全局配置文件,下面可以通過(guò)占位符的形式讀取<properties>指定文件中的值垃瞧。
  • 0或者N個(gè)<classPathEntry>標(biāo)簽蔫劣,<classPathEntry>只有一個(gè)location屬性,用于指定數(shù)據(jù)源驅(qū)動(dòng)包(jar或者zip)的絕對(duì)路徑个从,具體選擇什么驅(qū)動(dòng)包取決于連接什么類(lèi)型的數(shù)據(jù)源脉幢。
  • 1或者N個(gè)<context>標(biāo)簽,用于運(yùn)行時(shí)的解析模式和具體的代碼生成行為嗦锐,所以這個(gè)標(biāo)簽里面的配置是最重要的鸵隧。

下面分別列舉和分析一下<context>標(biāo)簽和它的主要子標(biāo)簽的一些屬性配置和功能。

context標(biāo)簽

<context>標(biāo)簽在mybatis-generator-core中對(duì)應(yīng)的實(shí)現(xiàn)類(lèi)為org.mybatis.generator.config.Context意推,它除了大量的子標(biāo)簽配置之外豆瘫,比較主要的屬性是:

  • idContext示例的唯一ID,用于輸出錯(cuò)誤信息時(shí)候作為唯一標(biāo)記菊值。

  • targetRuntime:用于執(zhí)行代碼生成模式外驱。

  • defaultModelType
    

    :控制

    Domain
    

    類(lèi)的生成行為。執(zhí)行引擎為

    MyBatis3DynamicSql
    

    或者

    MyBatis3Kotlin
    

    時(shí)忽略此配置腻窒,可選值:

    • conditional:默認(rèn)值昵宇,類(lèi)似hierarchical,但是只有一個(gè)主鍵的時(shí)候會(huì)合并所有屬性生成在同一個(gè)類(lèi)儿子。
    • flat:所有內(nèi)容全部生成在一個(gè)對(duì)象中瓦哎。
    • hierarchical:鍵生成一個(gè)XXKey對(duì)象,Blob等單獨(dú)生成一個(gè)對(duì)象,其他簡(jiǎn)單屬性在一個(gè)對(duì)象中蒋譬。

targetRuntime屬性的可選值比較多割岛,這里做個(gè)簡(jiǎn)單的小結(jié):

屬性 功能描述
MyBatis3DynamicSql 默認(rèn)值,兼容JDK8+MyBatis 3.4.2+犯助,不會(huì)生成XML映射文件癣漆,忽略<sqlMapGenerator>的配置項(xiàng),也就是Mapper全部注解化剂买,依賴(lài)于MyBatis Dynamic SQL類(lèi)庫(kù)
MyBatis3Kotlin 行為類(lèi)似于MyBatis3DynamicSql惠爽,不過(guò)兼容Kotlin的代碼生成
MyBatis3 提供基本的基于動(dòng)態(tài)SQLCRUD方法和XXXByExample方法,會(huì)生成XML映射文件
MyBatis3Simple 提供基本的基于動(dòng)態(tài)SQLCRUD方法瞬哼,會(huì)生成XML映射文件
MyBatis3DynamicSqlV1 已經(jīng)過(guò)時(shí)婚肆,不推薦使用

筆者偏向于把SQL文件和代碼分離,所以一般選用MyBatis3或者MyBatis3Simple坐慰。例如:

<context id="default" targetRuntime="MyBatis3">

<context>標(biāo)簽支持0或N個(gè)<property>標(biāo)簽旬痹,<property>的可選屬性有:

property屬性 功能描述 默認(rèn)值 備注
autoDelimitKeywords 是否使用分隔符號(hào)括住數(shù)據(jù)庫(kù)關(guān)鍵字 false 例如MySQL中會(huì)使用反引號(hào)括住關(guān)鍵字
beginningDelimiter 分隔符號(hào)的開(kāi)始符號(hào) "
endingDelimiter 分隔符號(hào)的結(jié)束號(hào) "
javaFileEncoding 文件的編碼 系統(tǒng)默認(rèn)值 來(lái)源于java.nio.charset.Charset
javaFormatter 類(lèi)名和文件格式化器 DefaultJavaFormatter 見(jiàn)JavaFormatterDefaultJavaFormatter
targetJava8 是否JDK8和啟動(dòng)其特性 true
kotlinFileEncoding Kotlin文件編碼 系統(tǒng)默認(rèn)值 來(lái)源于java.nio.charset.Charset
kotlinFormatter Kotlin類(lèi)名和文件格式化器 DefaultKotlinFormatter 見(jiàn)KotlinFormatterDefaultKotlinFormatter
xmlFormatter XML文件格式化器 DefaultXmlFormatter 見(jiàn)XmlFormatterDefaultXmlFormatter

jdbcConnection標(biāo)簽

<jdbcConnection>標(biāo)簽用于指定數(shù)據(jù)源的連接信息,它在mybatis-generator-core中對(duì)應(yīng)的實(shí)現(xiàn)類(lèi)為org.mybatis.generator.config.JDBCConnectionConfiguration讨越,主要屬性包括:

屬性 功能描述 是否必須
driverClass 數(shù)據(jù)源驅(qū)動(dòng)的全類(lèi)名 Y
connectionURL JDBC的連接URL Y
userId 連接到數(shù)據(jù)源的用戶名 N
password 連接到數(shù)據(jù)源的密碼 N

commentGenerator標(biāo)簽

<commentGenerator>標(biāo)簽是可選的两残,用于控制生成的實(shí)體的注釋內(nèi)容。它在mybatis-generator-core中對(duì)應(yīng)的實(shí)現(xiàn)類(lèi)為org.mybatis.generator.internal.DefaultCommentGenerator把跨,可以通過(guò)可選的type屬性指定一個(gè)自定義的CommentGenerator實(shí)現(xiàn)人弓。<commentGenerator>標(biāo)簽支持0或N個(gè)<property>標(biāo)簽,<property>的可選屬性有:

property屬性 功能描述 默認(rèn)值
suppressAllComments 是否生成注釋 false
suppressDate 是否在注釋中添加生成的時(shí)間戳 false
dateFormat 配合suppressDate使用着逐,指定輸出時(shí)間戳的格式 java.util.Date#toString()
addRemarkComments 是否輸出表和列的Comment信息 false

筆者建議保持默認(rèn)值崔赌,也就是什么注釋都不輸出,生成代碼干凈的實(shí)體耸别。

javaTypeResolver標(biāo)簽

<javaTypeResolver>標(biāo)簽是<context>的子標(biāo)簽健芭,用于解析和計(jì)算數(shù)據(jù)庫(kù)列類(lèi)型和Java類(lèi)型的映射關(guān)系,該標(biāo)簽只包含一個(gè)type屬性秀姐,用于指定org.mybatis.generator.api.JavaTypeResolver接口的實(shí)現(xiàn)類(lèi)慈迈。<javaTypeResolver>標(biāo)簽支持0或N個(gè)<property>標(biāo)簽,<property>的可選屬性有:

property屬性 功能描述 默認(rèn)值
forceBigDecimals 是否強(qiáng)制把所有的數(shù)字類(lèi)型強(qiáng)制使用java.math.BigDecimal類(lèi)型表示 false
useJSR310Types 是否支持JSR310省有,主要是JSR310的新日期類(lèi)型 false

如果useJSR310Types屬性設(shè)置為true痒留,那么生成代碼的時(shí)候類(lèi)型映射關(guān)系如下(主要針對(duì)日期時(shí)間類(lèi)型):

數(shù)據(jù)庫(kù)(JDBC)類(lèi)型 Java類(lèi)型
DATE java.time.LocalDate
TIME java.time.LocalTime
TIMESTAMP java.time.LocalDateTime
TIME_WITH_TIMEZONE java.time.OffsetTime
TIMESTAMP_WITH_TIMEZONE java.time.OffsetDateTime

引入mybatis-generator-core后,可以查看JavaTypeResolver的默認(rèn)實(shí)現(xiàn)為JavaTypeResolverDefaultImpl蠢沿,從它的源碼可以得知一些映射關(guān)系:

BIGINT --> Long
BIT --> Boolean
INTEGER --> Integer
SMALLINT --> Short
TINYINT --> Byte
......

有些時(shí)候伸头,我們希望INTEGERSMALLINTTINYINT都映射為Integer舷蟀,那么我們需要覆蓋JavaTypeResolverDefaultImpl的構(gòu)造方法:

public class DefaultJavaTypeResolver extends JavaTypeResolverDefaultImpl {

    public DefaultJavaTypeResolver() {
        super();
        typeMap.put(Types.SMALLINT, new JdbcTypeInformation("SMALLINT",
                new FullyQualifiedJavaType(Integer.class.getName())));
        typeMap.put(Types.TINYINT, new JdbcTypeInformation("TINYINT",
                new FullyQualifiedJavaType(Integer.class.getName())));
    }
}

注意一點(diǎn)的是這種自定義實(shí)現(xiàn)JavaTypeResolver接口的方式使用編程式運(yùn)行MBG會(huì)相對(duì)方便恤磷,如果需要使用Maven插件運(yùn)行面哼,那么需要把上面的DefaultJavaTypeResolver類(lèi)打包到插件中。

javaModelGenerator標(biāo)簽

<javaModelGenerator標(biāo)簽>標(biāo)簽是<context>的子標(biāo)簽扫步,主要用于控制實(shí)體(Model)類(lèi)的代碼生成行為魔策。它支持的屬性如下:

屬性 功能描述 是否必須 備注
targetPackage 生成的實(shí)體類(lèi)的包名 Y 例如club.throwable.model
targetProject 生成的實(shí)體類(lèi)文件相對(duì)于項(xiàng)目(根目錄)的位置 Y 例如src/main/java

<javaModelGenerator標(biāo)簽>標(biāo)簽支持0或N個(gè)<property>標(biāo)簽,<property>的可選屬性有:

property屬性 功能描述 默認(rèn)值 備注
constructorBased 是否生成一個(gè)帶有所有字段屬性的構(gòu)造函數(shù) false MyBatis3Kotlin模式下忽略此屬性配置
enableSubPackages 是否允許通過(guò)Schema生成子包 false 如果為true锌妻,例如包名為club.throwable代乃,如果Schemaxyz旬牲,那么實(shí)體類(lèi)文件最終會(huì)生成在club.throwable.xyz目錄
exampleTargetPackage 生成的伴隨實(shí)體類(lèi)的Example類(lèi)的包名 - -
exampleTargetProject 生成的伴隨實(shí)體類(lèi)的Example類(lèi)文件相對(duì)于項(xiàng)目(根目錄)的位置 - -
immutable 是否不可變 false 如果為true仿粹,則不會(huì)生成Setter方法,所有字段都使用final修飾原茅,提供一個(gè)帶有所有字段屬性的構(gòu)造函數(shù)
rootClass 為生成的實(shí)體類(lèi)添加父類(lèi) - 通過(guò)value指定父類(lèi)的全類(lèi)名即可
trimStrings Setter方法是否對(duì)字符串類(lèi)型進(jìn)行一次trim操作 false -

javaClientGenerator標(biāo)簽

<javaClientGenerator>標(biāo)簽是<context>的子標(biāo)簽吭历,主要用于控制Mapper接口的代碼生成行為。它支持的屬性如下:

屬性 功能描述 是否必須 備注
type Mapper接口生成策略 Y <context>標(biāo)簽的targetRuntime屬性為MyBatis3DynamicSql或者MyBatis3Kotlin時(shí)此屬性配置忽略
targetPackage 生成的Mapper接口的包名 Y 例如club.throwable.mapper
targetProject 生成的Mapper接口文件相對(duì)于項(xiàng)目(根目錄)的位置 Y 例如src/main/java

type屬性的可選值如下:

  • ANNOTATEDMAPPERMapper接口生成的時(shí)候依賴(lài)于注解和SqlProviders(也就是純注解實(shí)現(xiàn))擂橘,不會(huì)生成XML映射文件晌区。
  • XMLMAPPERMapper接口生成接口方法,對(duì)應(yīng)的實(shí)現(xiàn)代碼生成在XML映射文件中(也就是純映射文件實(shí)現(xiàn))通贞。
  • MIXEDMAPPERMapper接口生成的時(shí)候復(fù)雜的方法實(shí)現(xiàn)生成在XML映射文件中朗若,而簡(jiǎn)單的實(shí)現(xiàn)通過(guò)注解和SqlProviders實(shí)現(xiàn)(也就是注解和映射文件混合實(shí)現(xiàn))。

注意兩點(diǎn):

  • <context>標(biāo)簽的targetRuntime屬性指定為MyBatis3Simple的時(shí)候昌罩,type只能選用ANNOTATEDMAPPER或者XMLMAPPER哭懈。
  • <context>標(biāo)簽的targetRuntime屬性指定為MyBatis3的時(shí)候,type可以選用ANNOTATEDMAPPER茎用、XMLMAPPER或者MIXEDMAPPER遣总。

<javaClientGenerator>標(biāo)簽支持0或N個(gè)<property>標(biāo)簽,<property>的可選屬性有:

property屬性 功能描述 默認(rèn)值 備注
enableSubPackages 是否允許通過(guò)Schema生成子包 false 如果為true轨功,例如包名為club.throwable旭斥,如果Schemaxyz,那么Mapper接口文件最終會(huì)生成在club.throwable.xyz目錄
useLegacyBuilder 是否通過(guò)SQL Builder生成動(dòng)態(tài)SQL false
rootInterface 為生成的Mapper接口添加父接口 - 通過(guò)value指定父接口的全類(lèi)名即可

sqlMapGenerator標(biāo)簽

<sqlMapGenerator>標(biāo)簽是<context>的子標(biāo)簽古涧,主要用于控制XML映射文件的代碼生成行為垂券。它支持的屬性如下:

屬性 功能描述 是否必須 備注
targetPackage 生成的XML映射文件的包名 Y 例如mappings
targetProject 生成的XML映射文件相對(duì)于項(xiàng)目(根目錄)的位置 Y 例如src/main/resources

<sqlMapGenerator>標(biāo)簽支持0或N個(gè)<property>標(biāo)簽,<property>的可選屬性有:

property屬性 功能描述 默認(rèn)值 備注
enableSubPackages 是否允許通過(guò)Schema生成子包 false -

plugin標(biāo)簽

<plugin>標(biāo)簽是<context>的子標(biāo)簽羡滑,用于引入一些插件對(duì)代碼生成的一些特性進(jìn)行擴(kuò)展圆米,該標(biāo)簽只包含一個(gè)type屬性,用于指定org.mybatis.generator.api.Plugin接口的實(shí)現(xiàn)類(lèi)啄栓。內(nèi)置的插件實(shí)現(xiàn)見(jiàn)Supplied Plugins娄帖。例如:引入org.mybatis.generator.plugins.SerializablePlugin插件會(huì)讓生成的實(shí)體類(lèi)自動(dòng)實(shí)現(xiàn)java.io.Serializable接口并且添加serialVersionUID屬性咐刨。

table標(biāo)簽

<table>標(biāo)簽是<context>的子標(biāo)簽挠说,主要用于配置要生成代碼的數(shù)據(jù)庫(kù)表格,定制一些代碼生成行為等等均牢。它支持的屬性眾多,列舉如下:

屬性 功能描述 是否必須 備注
tableName 數(shù)據(jù)庫(kù)表名稱(chēng) Y 例如t_order
schema 數(shù)據(jù)庫(kù)Schema N -
catalog 數(shù)據(jù)庫(kù)Catalog N -
alias 表名稱(chēng)標(biāo)簽 N 如果指定了此值削葱,則查詢列的時(shí)候結(jié)果格式為alias_column
domainObjectName 表對(duì)應(yīng)的實(shí)體類(lèi)名稱(chēng)奖亚,可以通過(guò).指定包路徑 N 如果指定了bar.User,則包名為bar析砸,實(shí)體類(lèi)名稱(chēng)為User
mapperName 表對(duì)應(yīng)的Mapper接口類(lèi)名稱(chēng)昔字,可以通過(guò).指定包路徑 N 如果指定了bar.UserMapper,則包名為bar首繁,Mapper接口類(lèi)名稱(chēng)為UserMapper
sqlProviderName 動(dòng)態(tài)SQL提供類(lèi)SqlProvider的類(lèi)名稱(chēng) N -
enableInsert 是否允許生成insert方法 N 默認(rèn)值為true作郭,執(zhí)行引擎為MyBatis3DynamicSql或者MyBatis3Kotlin時(shí)忽略此配置
enableSelectByPrimaryKey 是否允許生成selectByPrimaryKey方法 N 默認(rèn)值為true,執(zhí)行引擎為MyBatis3DynamicSql或者MyBatis3Kotlin時(shí)忽略此配置
enableSelectByExample 是否允許生成selectByExample方法 N 默認(rèn)值為true弦疮,執(zhí)行引擎為MyBatis3DynamicSql或者MyBatis3Kotlin時(shí)忽略此配置
enableUpdateByPrimaryKey 是否允許生成updateByPrimaryKey方法 N 默認(rèn)值為true夹攒,執(zhí)行引擎為MyBatis3DynamicSql或者MyBatis3Kotlin時(shí)忽略此配置
enableDeleteByPrimaryKey 是否允許生成deleteByPrimaryKey方法 N 默認(rèn)值為true,執(zhí)行引擎為MyBatis3DynamicSql或者MyBatis3Kotlin時(shí)忽略此配置
enableDeleteByExample 是否允許生成deleteByExample方法 N 默認(rèn)值為true胁塞,執(zhí)行引擎為MyBatis3DynamicSql或者MyBatis3Kotlin時(shí)忽略此配置
enableCountByExample 是否允許生成countByExample方法 N 默認(rèn)值為true咏尝,執(zhí)行引擎為MyBatis3DynamicSql或者MyBatis3Kotlin時(shí)忽略此配置
enableUpdateByExample 是否允許生成updateByExample方法 N 默認(rèn)值為true,執(zhí)行引擎為MyBatis3DynamicSql或者MyBatis3Kotlin時(shí)忽略此配置
selectByPrimaryKeyQueryId value指定對(duì)應(yīng)的主鍵列提供列表查詢功能 N 執(zhí)行引擎為MyBatis3DynamicSql或者MyBatis3Kotlin時(shí)忽略此配置
selectByExampleQueryId value指定對(duì)應(yīng)的查詢ID提供列表查詢功能 N 執(zhí)行引擎為MyBatis3DynamicSql或者MyBatis3Kotlin時(shí)忽略此配置
modelType 覆蓋<context>defaultModelType屬性 N 見(jiàn)<context>defaultModelType屬性
escapeWildcards 是否對(duì)通配符進(jìn)行轉(zhuǎn)義 N -
delimitIdentifiers 標(biāo)記匹配表名稱(chēng)的時(shí)候是否需要使用分隔符去標(biāo)記生成的SQL N -
delimitAllColumns 是否所有的列都添加分隔符 N 默認(rèn)值為false啸罢,如果設(shè)置為true编检,所有列名會(huì)添加起始和結(jié)束分隔符

<table>標(biāo)簽支持0或N個(gè)<property>標(biāo)簽,<property>的可選屬性有:

property屬性 功能描述 默認(rèn)值 備注
constructorBased 是否為實(shí)體類(lèi)生成一個(gè)帶有所有字段的構(gòu)造函數(shù) false 執(zhí)行引擎為MyBatis3Kotlin的時(shí)候此屬性忽略
ignoreQualifiersAtRuntime 是否在運(yùn)行時(shí)忽略別名 false 如果為true扰才,則不會(huì)在生成表的時(shí)候把schemacatalog作為表的前綴
immutable 實(shí)體類(lèi)是否不可變 false 執(zhí)行引擎為MyBatis3Kotlin的時(shí)候此屬性忽略
modelOnly 是否僅僅生成實(shí)體類(lèi) false -
rootClass 如果配置此屬性允懂,則實(shí)體類(lèi)會(huì)繼承此指定的超類(lèi) - 如果有主鍵屬性會(huì)把主鍵屬性在超類(lèi)生成
rootInterface 如果配置此屬性,則實(shí)體類(lèi)會(huì)實(shí)現(xiàn)此指定的接口 - 執(zhí)行引擎為MyBatis3Kotlin或者MyBatis3DynamicSql的時(shí)候此屬性忽略
runtimeCatalog 指定運(yùn)行時(shí)的Catalog - 當(dāng)生成表和運(yùn)行時(shí)的表的Catalog不一樣的時(shí)候可以使用該屬性進(jìn)行配置
runtimeSchema 指定運(yùn)行時(shí)的Schema - 當(dāng)生成表和運(yùn)行時(shí)的表的Schema不一樣的時(shí)候可以使用該屬性進(jìn)行配置
runtimeTableName 指定運(yùn)行時(shí)的表名稱(chēng) - 當(dāng)生成表和運(yùn)行時(shí)的表的表名稱(chēng)不一樣的時(shí)候可以使用該屬性進(jìn)行配置
selectAllOrderByClause 指定字句內(nèi)容添加到selectAll()方法的order by子句之中 - 執(zhí)行引擎為MyBatis3Simple的時(shí)候此屬性才適用
trimStrings 實(shí)體類(lèi)的字符串類(lèi)型屬性會(huì)做trim處理 - 執(zhí)行引擎為MyBatis3Kotlin的時(shí)候此屬性忽略
useActualColumnNames 是否使用列名作為實(shí)體類(lèi)的屬性名 false -
useColumnIndexes XML映射文件中生成的ResultMap使用列索引定義而不是列名稱(chēng) false 執(zhí)行引擎為MyBatis3Kotlin或者MyBatis3DynamicSql的時(shí)候此屬性忽略
useCompoundPropertyNames 是否把列名和列備注拼接起來(lái)生成實(shí)體類(lèi)屬性名 false -

<table>標(biāo)簽還支持眾多的非property的子標(biāo)簽:

  • 0或1個(gè)<generatedKey>用于指定主鍵生成的規(guī)則训桶,指定此標(biāo)簽后會(huì)生成一個(gè)<selectKey>標(biāo)簽:
<!-- column:指定主鍵列 -->
<!-- sqlStatement:查詢主鍵的SQL語(yǔ)句累驮,例如填寫(xiě)了MySql,則使用SELECT LAST_INSERT_ID() -->
<!-- type:可選值為pre或者post舵揭,pre指定selectKey標(biāo)簽的order為BEFORE谤专,post指定selectKey標(biāo)簽的order為AFTER -->
<!-- identity:true的時(shí)候,指定selectKey標(biāo)簽的order為AFTER -->
<generatedKey column="id" sqlStatement="MySql" type="post" identity="true" />
  • 0或1個(gè)<domainObjectRenamingRule>用于指定實(shí)體類(lèi)重命名規(guī)則:
<!-- searchString中正則命中的實(shí)體類(lèi)名部分會(huì)替換為replaceString -->
<domainObjectRenamingRule searchString="^Sys" replaceString=""/>
<!-- 例如 SysUser會(huì)變成User -->
<!-- 例如 SysUserMapper會(huì)變成UserMapper -->
  • 0或1個(gè)<columnRenamingRule>用于指定列重命名規(guī)則:
<!-- searchString中正則命中的列名部分會(huì)替換為replaceString -->
<columnRenamingRule searchString="^CUST_" replaceString=""/>
<!-- 例如 CUST_BUSINESS_NAME會(huì)變成BUSINESS_NAME(useActualColumnNames=true) -->
<!-- 例如 CUST_BUSINESS_NAME會(huì)變成businessName(useActualColumnNames=false) -->
  • 0或N個(gè)<columnOverride>用于指定具體列的覆蓋映射規(guī)則:
<!-- column:指定要覆蓋配置的列 -->
<!-- property:指定要覆蓋配置的屬性 -->
<!-- delimitedColumnName:是否為列名添加定界符午绳,例如`{column}` -->
<!-- isGeneratedAlways:是否一定生成此列 -->
<columnOverride column="customer_name" property="customerName" javaType="" jdbcType="" typeHandler="" delimitedColumnName="" isGeneratedAlways="">
   <!-- 覆蓋table或者javaModelGenerator級(jí)別的trimStrings屬性配置 -->
   <property name="trimStrings" value="true"/>
<columnOverride/>
  • 0或N個(gè)<ignoreColumn>用于指定忽略生成的列:
<ignoreColumn column="version" delimitedColumnName="false"/>

實(shí)戰(zhàn)

如果需要深度定制一些代碼生成行為置侍,建議引入mybatis-generator-core并且通過(guò)編程式執(zhí)行代碼生成方法,否則可以選用Maven插件拦焚。假設(shè)我們?cè)诒镜財(cái)?shù)據(jù)local有一張t_order表如下:

CREATE TABLE `t_order`
(
    id           BIGINT UNSIGNED PRIMARY KEY COMMENT '主鍵',
    order_id     VARCHAR(64)    NOT NULL COMMENT '訂單ID',
    create_time  DATETIME       NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時(shí)間',
    amount       DECIMAL(10, 2) NOT NULL DEFAULT 0 COMMENT '金額',
    order_status TINYINT        NOT NULL DEFAULT 0 COMMENT '訂單狀態(tài)',
    UNIQUE uniq_order_id (`order_id`)
) COMMENT '訂單表';

假設(shè)項(xiàng)目的結(jié)構(gòu)如下:

mbg-sample
  - main
   - java
    - club
     - throwable
   - resources

下面會(huì)基于此前提舉三個(gè)例子蜡坊。編寫(xiě)基礎(chǔ)的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>
    <!-- 驅(qū)動(dòng)包絕對(duì)路徑 -->
    <classPathEntry
            location="I:\Develop\Maven-Repository\mysql\mysql-connector-java\5.1.48\mysql-connector-java-5.1.48.jar"/>

    <context id="default" targetRuntime="這里選擇合適的引擎">

        <property name="javaFileEncoding" value="UTF-8"/>

        <!-- 不輸出注釋 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/local"
                        userId="root"
                        password="root">
        </jdbcConnection>


        <!-- 不強(qiáng)制把所有的數(shù)字類(lèi)型轉(zhuǎn)化為BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <javaModelGenerator targetPackage="club.throwable.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="mappings" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <javaClientGenerator type="這里選擇合適的Mapper類(lèi)型" targetPackage="club.throwable.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <table tableName="t_order"
               enableCountByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               enableUpdateByExample="false"
               domainObjectName="Order"
               mapperName="OrderMapper">
            <generatedKey column="id" sqlStatement="MySql"/>
        </table>
    </context>
</generatorConfiguration>

純注解

使用純注解需要引入mybatis-dynamic-sql

<dependency>
    <groupId>org.mybatis.dynamic-sql</groupId>
    <artifactId>mybatis-dynamic-sql</artifactId>
    <version>1.1.4</version>
</dependency>

需要修改兩個(gè)位置:

<context id="default" targetRuntime="MyBatis3DynamicSql">
...

<javaClientGenerator type="ANNOTATEDMAPPER"
...

運(yùn)行結(jié)果會(huì)生成三個(gè)類(lèi):

// club.throwable.entity
public class Order {
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private Long id;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private String orderId;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private Date createTime;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private BigDecimal amount;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private Byte orderStatus;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public Long getId() {
        return id;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public void setId(Long id) {
        this.id = id;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public String getOrderId() {
        return orderId;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public Date getCreateTime() {
        return createTime;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public BigDecimal getAmount() {
        return amount;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public Byte getOrderStatus() {
        return orderStatus;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public void setOrderStatus(Byte orderStatus) {
        this.orderStatus = orderStatus;
    }
}

// club.throwable.dao
public final class OrderDynamicSqlSupport {
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final Order order = new Order();

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final SqlColumn<Long> id = order.id;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final SqlColumn<String> orderId = order.orderId;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final SqlColumn<Date> createTime = order.createTime;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final SqlColumn<BigDecimal> amount = order.amount;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final SqlColumn<Byte> orderStatus = order.orderStatus;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final class Order extends SqlTable {
        public final SqlColumn<Long> id = column("id", JDBCType.BIGINT);

        public final SqlColumn<String> orderId = column("order_id", JDBCType.VARCHAR);

        public final SqlColumn<Date> createTime = column("create_time", JDBCType.TIMESTAMP);

        public final SqlColumn<BigDecimal> amount = column("amount", JDBCType.DECIMAL);

        public final SqlColumn<Byte> orderStatus = column("order_status", JDBCType.TINYINT);

        public Order() {
            super("t_order");
        }
    }
}

@Mapper
public interface OrderMapper {
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    BasicColumn[] selectList = BasicColumn.columnList(id, orderId, createTime, amount, orderStatus);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @SelectProvider(type=SqlProviderAdapter.class, method="select")
    long count(SelectStatementProvider selectStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @DeleteProvider(type=SqlProviderAdapter.class, method="delete")
    int delete(DeleteStatementProvider deleteStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @InsertProvider(type=SqlProviderAdapter.class, method="insert")
    @SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="record.id", before=true, resultType=Long.class)
    int insert(InsertStatementProvider<Order> insertStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @SelectProvider(type=SqlProviderAdapter.class, method="select")
    @Results(id="OrderResult", value = {
        @Result(column="id", property="id", jdbcType=JdbcType.BIGINT, id=true),
        @Result(column="order_id", property="orderId", jdbcType=JdbcType.VARCHAR),
        @Result(column="create_time", property="createTime", jdbcType=JdbcType.TIMESTAMP),
        @Result(column="amount", property="amount", jdbcType=JdbcType.DECIMAL),
        @Result(column="order_status", property="orderStatus", jdbcType=JdbcType.TINYINT)
    })
    Optional<Order> selectOne(SelectStatementProvider selectStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @SelectProvider(type=SqlProviderAdapter.class, method="select")
    @Results(id="OrderResult", value = {
        @Result(column="id", property="id", jdbcType=JdbcType.BIGINT, id=true),
        @Result(column="order_id", property="orderId", jdbcType=JdbcType.VARCHAR),
        @Result(column="create_time", property="createTime", jdbcType=JdbcType.TIMESTAMP),
        @Result(column="amount", property="amount", jdbcType=JdbcType.DECIMAL),
        @Result(column="order_status", property="orderStatus", jdbcType=JdbcType.TINYINT)
    })
    List<Order> selectMany(SelectStatementProvider selectStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @UpdateProvider(type=SqlProviderAdapter.class, method="update")
    int update(UpdateStatementProvider updateStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default long count(CountDSLCompleter completer) {
        return MyBatis3Utils.countFrom(this::count, order, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int delete(DeleteDSLCompleter completer) {
        return MyBatis3Utils.deleteFrom(this::delete, order, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int deleteByPrimaryKey(Long id_) {
        return delete(c -> 
            c.where(id, isEqualTo(id_))
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int insert(Order record) {
        return MyBatis3Utils.insert(this::insert, record, order, c ->
            c.map(id).toProperty("id")
            .map(orderId).toProperty("orderId")
            .map(createTime).toProperty("createTime")
            .map(amount).toProperty("amount")
            .map(orderStatus).toProperty("orderStatus")
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int insertSelective(Order record) {
        return MyBatis3Utils.insert(this::insert, record, order, c ->
            c.map(id).toProperty("id")
            .map(orderId).toPropertyWhenPresent("orderId", record::getOrderId)
            .map(createTime).toPropertyWhenPresent("createTime", record::getCreateTime)
            .map(amount).toPropertyWhenPresent("amount", record::getAmount)
            .map(orderStatus).toPropertyWhenPresent("orderStatus", record::getOrderStatus)
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default Optional<Order> selectOne(SelectDSLCompleter completer) {
        return MyBatis3Utils.selectOne(this::selectOne, selectList, order, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default List<Order> select(SelectDSLCompleter completer) {
        return MyBatis3Utils.selectList(this::selectMany, selectList, order, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default List<Order> selectDistinct(SelectDSLCompleter completer) {
        return MyBatis3Utils.selectDistinct(this::selectMany, selectList, order, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default Optional<Order> selectByPrimaryKey(Long id_) {
        return selectOne(c ->
            c.where(id, isEqualTo(id_))
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int update(UpdateDSLCompleter completer) {
        return MyBatis3Utils.update(this::update, order, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    static UpdateDSL<UpdateModel> updateAllColumns(Order record, UpdateDSL<UpdateModel> dsl) {
        return dsl.set(id).equalTo(record::getId)
                .set(orderId).equalTo(record::getOrderId)
                .set(createTime).equalTo(record::getCreateTime)
                .set(amount).equalTo(record::getAmount)
                .set(orderStatus).equalTo(record::getOrderStatus);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    static UpdateDSL<UpdateModel> updateSelectiveColumns(Order record, UpdateDSL<UpdateModel> dsl) {
        return dsl.set(id).equalToWhenPresent(record::getId)
                .set(orderId).equalToWhenPresent(record::getOrderId)
                .set(createTime).equalToWhenPresent(record::getCreateTime)
                .set(amount).equalToWhenPresent(record::getAmount)
                .set(orderStatus).equalToWhenPresent(record::getOrderStatus);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int updateByPrimaryKey(Order record) {
        return update(c ->
            c.set(orderId).equalTo(record::getOrderId)
            .set(createTime).equalTo(record::getCreateTime)
            .set(amount).equalTo(record::getAmount)
            .set(orderStatus).equalTo(record::getOrderStatus)
            .where(id, isEqualTo(record::getId))
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int updateByPrimaryKeySelective(Order record) {
        return update(c ->
            c.set(orderId).equalToWhenPresent(record::getOrderId)
            .set(createTime).equalToWhenPresent(record::getCreateTime)
            .set(amount).equalToWhenPresent(record::getAmount)
            .set(orderStatus).equalToWhenPresent(record::getOrderStatus)
            .where(id, isEqualTo(record::getId))
        );
    }
}

極簡(jiǎn)XML映射文件

極簡(jiǎn)XML映射文件生成只需要簡(jiǎn)單修改配置文件:

<context id="default" targetRuntime="MyBatis3Simple">
...

<javaClientGenerator type="XMLMAPPER"
...

生成三個(gè)文件:

// club.throwable.entity
public class Order {
    private Long id;

    private String orderId;

    private Date createTime;

    private BigDecimal amount;

    private Byte orderStatus;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    public Byte getOrderStatus() {
        return orderStatus;
    }

    public void setOrderStatus(Byte orderStatus) {
        this.orderStatus = orderStatus;
    }
}

// club.throwable.dao
public interface OrderMapper {
    int deleteByPrimaryKey(Long id);

    int insert(Order record);

    Order selectByPrimaryKey(Long id);

    List<Order> selectAll();

    int updateByPrimaryKey(Order record);
}

// mappings
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="club.throwable.dao.OrderMapper">
    <resultMap id="BaseResultMap" type="club.throwable.entity.Order">
        <id column="id" jdbcType="BIGINT" property="id"/>
        <result column="order_id" jdbcType="VARCHAR" property="orderId"/>
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
        <result column="amount" jdbcType="DECIMAL" property="amount"/>
        <result column="order_status" jdbcType="TINYINT" property="orderStatus"/>
    </resultMap>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
        delete
        from t_order
        where id = #{id,jdbcType=BIGINT}
    </delete>
    <insert id="insert" parameterType="club.throwable.entity.Order">
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into t_order (order_id, create_time, amount,
        order_status)
        values (#{orderId,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{amount,jdbcType=DECIMAL},
        #{orderStatus,jdbcType=TINYINT})
    </insert>
    <update id="updateByPrimaryKey" parameterType="club.throwable.entity.Order">
        update t_order
        set order_id     = #{orderId,jdbcType=VARCHAR},
            create_time  = #{createTime,jdbcType=TIMESTAMP},
            amount       = #{amount,jdbcType=DECIMAL},
            order_status = #{orderStatus,jdbcType=TINYINT}
        where id = #{id,jdbcType=BIGINT}
    </update>
    <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
        select id, order_id, create_time, amount, order_status
        from t_order
        where id = #{id,jdbcType=BIGINT}
    </select>
    <select id="selectAll" resultMap="BaseResultMap">
        select id, order_id, create_time, amount, order_status
        from t_order
    </select>
    <resultMap id="BaseResultMap" type="club.throwable.entity.Order">
        <id column="id" jdbcType="BIGINT" property="id"/>
        <result column="order_id" jdbcType="VARCHAR" property="orderId"/>
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
        <result column="amount" jdbcType="DECIMAL" property="amount"/>
        <result column="order_status" jdbcType="TINYINT" property="orderStatus"/>
    </resultMap>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
        delete
        from t_order
        where id = #{id,jdbcType=BIGINT}
    </delete>
    <insert id="insert" parameterType="club.throwable.entity.Order">
        <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.Long">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into t_order (id, order_id, create_time,
        amount, order_status)
        values (#{id,jdbcType=BIGINT}, #{orderId,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP},
        #{amount,jdbcType=DECIMAL}, #{orderStatus,jdbcType=TINYINT})
    </insert>
    <update id="updateByPrimaryKey" parameterType="club.throwable.entity.Order">
        update t_order
        set order_id     = #{orderId,jdbcType=VARCHAR},
            create_time  = #{createTime,jdbcType=TIMESTAMP},
            amount       = #{amount,jdbcType=DECIMAL},
            order_status = #{orderStatus,jdbcType=TINYINT}
        where id = #{id,jdbcType=BIGINT}
    </update>
    <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
        select id, order_id, create_time, amount, order_status
        from t_order
        where id = #{id,jdbcType=BIGINT}
    </select>
    <select id="selectAll" resultMap="BaseResultMap">
        select id, order_id, create_time, amount, order_status
        from t_order
    </select>
</mapper>

編程式自定義類(lèi)型映射

筆者喜歡把所有的非長(zhǎng)整型的數(shù)字,統(tǒng)一使用Integer接收赎败,因此需要自定義類(lèi)型映射秕衙。編寫(xiě)映射器如下:

public class DefaultJavaTypeResolver extends JavaTypeResolverDefaultImpl {

    public DefaultJavaTypeResolver() {
        super();
        typeMap.put(Types.SMALLINT, new JdbcTypeInformation("SMALLINT",
                new FullyQualifiedJavaType(Integer.class.getName())));
        typeMap.put(Types.TINYINT, new JdbcTypeInformation("TINYINT",
                new FullyQualifiedJavaType(Integer.class.getName())));
    }
}

此時(shí)最好使用編程式運(yùn)行代碼生成器,修改XML配置文件:

<javaTypeResolver type="club.throwable.mbg.DefaultJavaTypeResolver">
        <property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
...

運(yùn)行方法代碼如下:

public class Main {

    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<>();
        // 如果已經(jīng)存在生成過(guò)的文件是否進(jìn)行覆蓋
        boolean overwrite = true;
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(Main.class.getResourceAsStream("/generator-configuration.xml"));
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator generator = new MyBatisGenerator(config, callback, warnings);
        generator.generate(null);
    }
}

數(shù)據(jù)庫(kù)的order_statusTINYINT類(lèi)型僵刮,生成出來(lái)的文件中的orderStatus字段全部替換使用Integer類(lèi)型定義据忘。

小結(jié)

本文相對(duì)詳盡地介紹了Mybatis Generator的使用方式鹦牛,具體分析了XML配置文件中主要標(biāo)簽以及標(biāo)簽屬性的功能。因?yàn)?code>Mybatis在JavaORM框架體系中還會(huì)有一段很長(zhǎng)的時(shí)間處于主流地位勇吊,了解Mybatis Generator可以簡(jiǎn)化CRUD方法模板代碼曼追、實(shí)體以及Mapper接口代碼生成,從而解放大量生產(chǎn)力汉规。Mybatis Generator有不少第三方的擴(kuò)展礼殊,例如tk.mapper或者mybatis-plus自身的擴(kuò)展,可能附加的功能不一樣针史,但是基本的使用是一致的晶伦。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市悟民,隨后出現(xiàn)的幾起案子坝辫,更是在濱河造成了極大的恐慌篷就,老刑警劉巖射亏,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異竭业,居然都是意外死亡智润,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)未辆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)窟绷,“玉大人,你說(shuō)我怎么就攤上這事咐柜〖骝冢” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵拙友,是天一觀的道長(zhǎng)为狸。 經(jīng)常有香客問(wèn)我,道長(zhǎng)遗契,這世上最難降的妖魔是什么辐棒? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮牍蜂,結(jié)果婚禮上漾根,老公的妹妹穿的比我還像新娘。我一直安慰自己鲫竞,他們只是感情好辐怕,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著从绘,像睡著了一般寄疏。 火紅的嫁衣襯著肌膚如雪其做。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,754評(píng)論 1 307
  • 那天赁还,我揣著相機(jī)與錄音妖泄,去河邊找鬼。 笑死艘策,一個(gè)胖子當(dāng)著我的面吹牛蹈胡,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播朋蔫,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼罚渐,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了驯妄?” 一聲冷哼從身側(cè)響起荷并,我...
    開(kāi)封第一講書(shū)人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎青扔,沒(méi)想到半個(gè)月后源织,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡微猖,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年谈息,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片凛剥。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡侠仇,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出犁珠,到底是詐尸還是另有隱情逻炊,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布犁享,位于F島的核電站余素,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏饼疙。R本人自食惡果不足惜溺森,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望窑眯。 院中可真熱鬧屏积,春花似錦、人聲如沸磅甩。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)卷要。三九已至渣聚,卻和暖如春独榴,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背奕枝。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工棺榔, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人隘道。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓症歇,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親谭梗。 傳聞我的和親對(duì)象是個(gè)殘疾皇子忘晤,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容