MyBatis积累(1):MyBatis Generator 超详细配置

目录

1、MyBatis Generator

2、MyBatis Generator 插件

2.1、 pom 中引入 MyBatis Generator 插件

2.2、配置 MyBatis Generator 插件

2.2.1、配置 MyBatis Generator config 文件路径

2.2.2、允许覆盖生成的文件

2.2.3、添加数据库驱动依赖

2.2.4、添加其他依赖

2.2.5、mybatis-generator-core 依赖

2.3、配置 MyBatis Generator Config

2.3.1、mybatis-generator-config详情

2.3.2、引入外部配置文件

2.3.3、配置context

2.3.4、context的子元素

plugin

commentGenerator

jdbcConnection

javaTypeResolver

javaModelGenerator

sqlMapGenerator

table

2.4、使用 MyBatis Generator


1、MyBatis Generator

    MyBatis Generator 是 MyBatis 提供的一个代码生成工具。可以帮我们生成 表对应的持久化对象(po)、操作数据库的接口(dao)、CRUD sql的xml(mapper)

     MyBatis Generator 是一个独立工具,可以下载jar包来运行,也可以在 Ant 和 maven 运行。

2、MyBatis Generator 插件

2.1、 pom 中引入 MyBatis Generator 插件

在 pom 的根节点下添加以下配置

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.7</version>
        </plugin>
    <plugins>    
</build>

2.2、配置 MyBatis Generator 插件

光引入 MyBatis Generator 插件还不行,还得配置 MyBatis Generator插件

2.2.1、配置 MyBatis Generator config 文件路径

MyBatis Generator 插件需要根据一个 MyBatis Generator config 文件,来具体运行

配置如下,版本是 1.3.7

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.7</version>
            <configuration>
                <!--mybatis的代码生成器的配置文件-->
                <configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
            </configuration>
        </plugin>
    <plugins>    
</build>

注意,这个路径是你的配置文件相对于该 pom 文件的路径

2.2.2、允许覆盖生成的文件

有时候我们的数据库表添加了新字段,需要重新生成对应的文件。常规做法是手动删除旧文件,然后在用 MyBatis Generator 生成新文件。当然你也可以选择让 MyBatis Generator 覆盖旧文件,省下手动删除的步骤。

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.7</version>
            <configuration>
                <!--mybatis的代码生成器的配置文件-->
                <configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
                <!--允许覆盖生成的文件-->
                <overwrite>true</overwrite>
            </configuration>
        </plugin>
    <plugins>    
</build>

值得注意的是,MyBatis Generator 只会覆盖旧的 po、dao、而 *mapper.xml 不会覆盖,而是追加,这样做的目的是防止用户自己写的 sql 语句一不小心都被 MyBatis Generator 给覆盖了

2.2.3、添加数据库驱动依赖

MyBatis Generator 需要链接数据库,肯定是需要对应数据库驱动的依赖的。

如下,给 MyBatis Generator 添加数据库驱动依赖

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.7</version>
            <configuration>
                <!--mybatis的代码生成器的配置文件-->
                <configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
                <!--允许覆盖生成的文件-->
                <overwrite>true</overwrite>
            </configuration>
            <dependencies>
                <!-- mysql的JDBC驱动 -->
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.17</version>
                </dependency>
            </dependencies>
        </plugin>
    <plugins>    
</build>

我用的数据库是 mysql ,其他数据库同理。注意数据库驱动的版本号,不同的版本对应的 MyBatis Generator 配置有些许不同,之后会讲。

大部分情况下,我们的项目中已经配置过了对应数据库的JDBC驱动,如下

现在在插件中又配置一次,感觉有些冗余,maven 提供了 includeCompileDependencies 属性,让我们在插件中引用 dependencies 的依赖,这样就不需要重复配置了。

配置如下

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.7</version>
            <configuration>
                <!--mybatis的代码生成器的配置文件-->
                <configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
                <!--允许覆盖生成的文件-->
                <overwrite>true</overwrite>
                <!--将当前pom的依赖项添加到生成器的类路径中-->
                <includeCompileDependencies>true</includeCompileDependencies>
            </configuration>
        </plugin>
    <plugins>    
</build>

2.2.4、添加其他依赖

一般配置了 includeCompileDependencies 后就不需要配置其他依赖了,因为 includeCompileDependencies 会将当前 pom 的 dependencies 中所以 Compile 期的依赖全部添加到生成器的类路径中。

但有的人不想配置 includeCompileDependencies ,或者想在MyBatis Generator插件中使用另一个版本的依赖,就可以配置 dependencies

2.2.5、mybatis-generator-core 依赖

网上大部分文章都会配置 mybatis-generator-core 这个依赖,但是 MyBatis Generator 官网的案例中都没有提到说要配置这个依赖,我没有配置,并且可以正常使用 MyBatis Generator

2.3、配置 MyBatis Generator Config

2.3.1、mybatis-generator-config详情

MyBatis Generator 插件启动后,会根据你在 pom 中配置都路径找到该配置文件。

这个配置文件才是详细都配置 MyBatis Generator 生成代码的各种细节。

其中最重要的就是 context ,你的配置文件至少得包含一个context

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

    <!-- 一个数据库一个context, context子元素必须按照如下顺序
        property*、plugin*、commentGenerator?、jdbcConnection、javaTypeResolver?
        javaModelGenerator、sqlMapGenerator?、javaClientGenerator?、table+
    -->
    <context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat">
        <!-- 生成的pojo,将implements Serializable -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
        <!-- 生成的pojo,增加了equals 和 hashCode方法-->
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"></plugin>

        <commentGenerator type="com.crane.spring.comment.MyCommentGenerator">
<!--            &lt;!&ndash; 是否去除自动生成的注释 true:是 : false:否 &ndash;&gt;-->
<!--            <property name="suppressAllComments" value="true" />-->
<!--            &lt;!&ndash; 添加 db 表中字段的注释 &ndash;&gt;-->
<!--            <property name="addRemarkComments" value="true"/>-->
<!--            &lt;!&ndash; 不希望生成的注释中包含时间戳 &ndash;&gt;-->
<!--            <property name="suppressDate" value="true"/>-->
        </commentGenerator>

        <!-- 数据库链接URL、用户名、密码 -->
        <jdbcConnection driverClass="${spring.datasource.driver-class-name}"
                        connectionURL="${spring.datasource.url}"
                        userId="${spring.datasource.username}"
                        password="${spring.datasource.password}">
        </jdbcConnection>

        <javaTypeResolver>
            <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL
           和 NUMERIC 类型解析为java.math.BigDecimal -->
            <property name="forceBigDecimals" value="false" />
            <!--默认false
                false,将所有 JDBC 的时间类型解析为 java.util.Date
                true,将 JDBC 的时间类型按如下规则解析
                   DATE	                -> java.time.LocalDate
                   TIME	                -> java.time.LocalTime
                   TIMESTAMP                   -> java.time.LocalDateTime
                   TIME_WITH_TIMEZONE  	-> java.time.OffsetTime
                   TIMESTAMP_WITH_TIMEZONE	-> java.time.OffsetDateTime
       -->
            <property name="useJSR310Types" value="false"/>
        </javaTypeResolver>

        <!-- 生成model模型,对应的包路径,以及文件存放路径(targetProject),targetProject可以指定具体的路径,如src/main/java,
            也可以使用“MAVEN”来自动生成,这样生成的代码会在target/generated-source目录下 -->
        <!--<javaModelGenerator targetPackage="com.joey.mybaties.test.pojo" targetProject="MAVEN"> -->
        <javaModelGenerator targetPackage="com.crane.spring.po"
                            targetProject="src/main/java">
            <!-- 是否让schema作为包的后缀, 默认是false  -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格
                  是否针对string类型的字段在set方法中进行修剪,默认false    -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--对应的mapper.xml文件 -->
        <sqlMapGenerator targetPackage="mappers"
                         targetProject="src/main/resources">
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- 对应的Mapper接口类文件
         type="XMLMAPPER" 会将接口的实现放在 mapper.xml中,也推荐这样配置。
         type="ANNOTATEDMAPPER",接口的实现通过注解写在接口上面
         -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.crane.spring.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>


        <!-- 列出要生成代码的所有表,这里配置的是不生成Example文件 -->
        <table tableName="userinfo" domainObjectName="UserInfoPO"
               enableCountByExample="true" enableUpdateByExample="true"
               enableDeleteByExample="true" enableSelectByExample="true"
               selectByExampleQueryId="true">
            <!--是否使用实际列名,默认为false-->
            <property name="useActualColumnNames" value="false" />
        </table>
    </context>


</generatorConfiguration>

2.3.2、引入外部配置文件

MyBatis Generator config 是可以引入外部配置文件的,如下,路径为相对于当前配置文件的路径

2.3.3、配置context

注意是配置在 <generatorConfiguration> 下

<context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat">

</context>
  • id : 随便填,保证多个 context id 不重复就行
  • defaultModelType : 可以不填,默认值 conditionalflat表示一张表对应一个po
  • targetRuntime :可以不填,默认值 MyBatis3,常用的还有 MyBatis3Simple,这个配置会影响生成的 dao 和 mapper.xml的内容

targetRuntime = MyBatis3,生成的 dao 和 mapper.xml 如下

targetRuntime = MyBatis3Simple,生成的 dao 和 mapper.xml 如下,接口会少很多,只包含最最常用的

2.3.4、context的子元素

context的子元素必须按照以下给出的个数、顺序配置

  1. property (0..N)
  2. plugin (0..N)
  3. commentGenerator (0 or 1)
  4. jdbcConnection (需要connectionFactory 或 jdbcConnection)
  5. javaTypeResolver (0 or 1)
  6. javaModelGenerator (至少1个)
  7. sqlMapGenerator (0 or 1)
  8. javaClientGenerator (0 or 1)
  9. table (1..N)

plugin

配置一个插件,例如

<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
复制代码

这个插件给生成的Java模型对象增加了equals和hashCode方法

commentGenerator

commentGenerator 用来配置生成的注释。默认是生成注释的,并且会生成时间戳,如下

如果你想要保留注释和时间戳,可以不配置 commentGenerator

如果你不想保留时间戳,需要如下配置

<commentGenerator>
    <!-- 不希望生成的注释中包含时间戳 -->
    <property name="suppressDate" value="true"/>
</commentGenerator>
复制代码

默认生成的注释是不会有 db 表中字段的注释,如果你想知道每个字段在数据库中的含义(前提是数据库中对应表的字段你添加了注释),可以如下配置

<commentGenerator>
    <!-- 添加 db 表中字段的注释 -->
    <property name="addRemarkComments" value="true"/>
</commentGenerator>

但说实话,MyBatis Generator 生成注释无用信息太多了,所以我一般都选择不生成注释

<commentGenerator>
    <!-- 是否不生成注释 -->
    <property name="suppressAllComments" value="true"/>
</commentGenerator>

jdbcConnection

MyBatis Generator 需要链接数据库,所以需要配置 jdbcConnection,具体如下

<jdbcConnection driverClass="${spring.datasource.driverClassName}"
                connectionURL="${spring.datasource.url}"
                userId="${spring.datasource.username}"
                password="${spring.datasource.password}">
    <!--高版本的 mysql-connector-java 需要设置 nullCatalogMeansCurrent=true-->
    <property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>

${}里面是外部配置文件中的"name"

也可以写死,那就不需要配置<properties resource="application-dev.properties"/>

文章 MyBatis Generator踩坑与自救

javaTypeResolver

javaTypeResolver 是配置 JDBC 与 java 的类型转换规则,或者你也可以不用配置,使用它默认的转换规则。

就算配置也只能配置 bigDecimal 类型和时间类型的转换

<javaTypeResolver>
    <!--是否使用 bigDecimal,默认false。
        false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer
        true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal-->
    <property name="forceBigDecimals" value="true"/>
    <!--默认false
        false,将所有 JDBC 的时间类型解析为 java.util.Date
        true,将 JDBC 的时间类型按如下规则解析
            DATE	                -> java.time.LocalDate
            TIME	                -> java.time.LocalTime
            TIMESTAMP                   -> java.time.LocalDateTime
            TIME_WITH_TIMEZONE  	-> java.time.OffsetTime
            TIMESTAMP_WITH_TIMEZONE	-> java.time.OffsetDateTime
        -->
    <property name="useJSR310Types" value="true"/>
</javaTypeResolver>

javaModelGenerator

配置 po 生成的包路径和项目路径,如下

<javaModelGenerator targetPackage="com.wqlm.boot.user.po" targetProject="src/main/java">
    <!-- 是否让schema作为包的后缀,默认为false -->
    <!--<property name="enableSubPackages" value="false"/>-->
    <!-- 是否针对string类型的字段在set方法中进行修剪,默认false -->
    <property name="trimStrings" value="true"/>
</javaModelGenerator>

<property name="trimStrings" value="true"/> 生成出来的 set 方法如下

<property name="enableSubPackages" value="true"/> 时,可能会在 po 目录下在创建一个 “数据库名” 的文件夹,生成的 po 会放在该文件夹下,也就是说会多一层目录,用的上的可以配置

sqlMapGenerator

配置 Mapper.xml 文件的生成目录

<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
    <!--<property name="enableSubPackages" value="false"/>-->
</sqlMapGenerator>

javaClientGenerator

配置 XxxMapper.java 文件的生成目录

<javaClientGenerator targetPackage="com.wqlm.boot.user.dao" targetProject="src/main/java" type="XMLMAPPER">
    <!--<property name="enableSubPackages" value="false"/>-->
</javaClientGenerator>

type="XMLMAPPER" 会将接口的实现放在 mapper.xml中,也推荐这样配置。也可以设置 type 为其他值,比如 type="ANNOTATEDMAPPER",接口的实现通过注解写在接口上面,如图

如果采用这种方式,不会生成 mapper.xml 也不用配置 <sqlMapGenerator>,但是采用注解来实现接口应对简单查询还好,如果是复杂查询并不如xml方便,所以还是建议将type配置成XMLMAPPER

table

一个 table 对应一张表,如果想同时生成多张表,需要配置多个 table

<!-- schema为数据库名,oracle需要配置,mysql不需要配置。
     tableName为对应的数据库表名
     domainObjectName 是要生成的实体类名(可以不指定)
     enableXXXByExample 默认为 true, 为 true 会生成一个对应Example帮助类,帮助你进行条件查询,不想要可以设为false
     -->
<table schema="" tableName="user" domainObjectName="User"
       enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
       enableUpdateByExample="false" selectByExampleQueryId="false">
    <!--是否使用实际列名,默认为false-->
    <!--<property name="useActualColumnNames" value="false" />-->
</table>
复制代码

其中 domainObjectName 不配置时,它会按照帕斯卡命名法将表名转换成类名

enableXXXByExample 默认为true,但只有在targetRuntime="MyBatis3"时才生效

生效时,会在po下多生成一个 XxxExample.java 的文件,如下

一个简单的user的Example帮助类有470行,我一般不会去用,如上全设置为false

targetRuntime="MyBatis3Simple"时,enableXXXByExample 不管为true、还是false 都不生效。

2.4、使用 MyBatis Generator

 配置好后,双击 maven 中的 MyBatis Generator 运行

参考:MyBatis Generator 超详细配置 - 掘金

Mybatis代码生成器Mybatis-Generator使用详解 - throwable - 博客园

  • 10
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值