【mybatis-generator】mybatis代码生成器generator,生成文件名自定义配置

MyBatis-Generator 使用

一. 引入依赖和相关插件

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.0</version>
        </dependency>
  <build>
        <plugins>
            <!--  引入 MyBatis-Generator 插件,在通过 Maven 的插件运行 MBG 时有效 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.6</version>
                <configuration>
                    <!--  引入 MyBatis-Generator 的配置文件 -->
                    <configurationFile>./src/main/resources/mybatis-generator-config.xml</configurationFile>
                    <!--  允许 MBG 将构建消息写入日志中  -->
                    <verbose>true</verbose>
                    <!--  再次运行 MBG 时,允许覆盖已生成的文件,但是不会覆盖 xml 文件  -->
                    <overwrite>true</overwrite>
                </configuration>

                <dependencies>
                    <!--  引入 mysql 的 JDBC 驱动,否则会报错找不到驱动  -->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>com.itfsw</groupId>
                        <artifactId>mybatis-generator-plugin</artifactId>
                        <version>1.3.10</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

二.设置配置文件


<!-- 所有的配置均在 generatorConfiguration 标签下 -->
<generatorConfiguration>

    <!-- 引入外部配置文件   -->
    <properties resource="mybatis-generator.properties"/>
    <!--  加载需要的额外的依赖包 -->
    <!--  <classPathEntry location="/Users/deecyn/Files/db2java.zip"/>-->

    <!-- 配置 context 上下文  -->
    <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">

        <!-- 自动识别数据库关键字,默认为 false,一般保留默认值,遇到数据库关键字(Java关键字)时,
            按照 table 元素中 columnOverride 属性的配置进行覆盖;
            如果设置为 true, 则需按照 SqlReservedWords 中定义的关键字列表,对关键字进行定界(分隔);
            定界符(分隔符)参见 beginningDelimiter 和 endingDelimiter 的设置-->
        <property name="autoDelimitKeywords" value="false"/>

        <!-- beginningDelimiter 和 endingDelimiter,定界符(分隔符),指明用于标记数据库关键字的符号,默认为为双引号 (");
              在 oracle 中是双引号 ("),在 MySQL 中需配置为反引号 (`)  -->
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <!-- 生成的 Java 文件的编码   -->
        <property name="JavaFileEncoding" value="UTF-8"/>
        <!-- 格式化 Java 代码 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!-- 格式化 XML 代码 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>


        <!-- 使生成的 Model 实现 Serializable 接口 -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <!--  为生成的 Model 覆写 toString() 方法 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <!--  为生成的 Model 覆写 equals() 和 hashCode() 方法 -->
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
        <!-- 数据Model属性对应Column获取插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
        <!-- 批量插入插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.BatchInsertPlugin"/>

        <!--  配置注释生成器 -->
        <commentGenerator>
            <!--  不生成所有注释,默认为 false  -->
            <property name="suppressAllComments" value="true"/>

            <!--  生成的注释中不包含时间信息,默认为 false -->
            <property name="suppressDate" value="true"/>
            <!--  生成的注释中,时间的显示格式 -->
            <property name="dateFormat" value="yyyy/MM/dd"/>
            <!-- 是否添加数据库表中字段的注释,默认为 false  -->
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
        <!--    引用自定义的注释生成器 -->
        <!--  <commentGenerator  type="deecyn.shop_02.mbg.MyCommentGenerator" >
                    <property name="author" value="Deecyn"/>
             </commentGenerator>-->

        <!--  配置数据库连接  -->
        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.connectionURL}"
                        userId="${jdbc.userId}"
                        password="${jdbc.password}">

            <!--  若为 8.0 版本以上的 mysql-connector-java 驱动,需要设置 nullCatalogMeansCurrent = true -->
            <!--  <property name="nullCatalogMeansCurrent" value="true"/> -->
        </jdbcConnection>

        <!--  配置类型转换规则  -->
        <javaTypeResolver>
            <!-- 是否强制使用 BigDecimal;
                默认为 false,把 JDBC 的 DECIMAL 和 NUMERIC 类型解析为 Integer;
                设置为 true 时,把 JDBC 的 DECIMAL 和 NUMERIC 类型解析为 java.math.BigDecimal -->
            <property name="forceBigDecimals" value="true"/>

            <!-- 设置时间类型的转换,
               默认 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>

        <!--  配置 Java 模型生成器 -->
        <javaModelGenerator targetPackage="${package.model}" targetProject="src/main/java">
            <!-- 自动为每一个生成的类创建一个构造方法,构造方法包含了所有的 field,而不是使用 setter;
              默认值为 false -->
            <property name="constructorBased" value="false"/>

            <!-- 在 targetPackage 的基础上,根据数据库的 schema 再生成一层 package,
            最终生成的类放在这个package下;默认为false -->
            <property name="enableSubPackages" value="false"/>

            <!-- 是否创建一个不可变的类:如果为true,那么 MBG 生成的类会没有 setter 方法,
            采用构造函数的方式来接收和设置每个字段的值,此时会忽略 constructorBased 属性的设置;
            默认值为 false  -->
            <property name="immutable" value="false"/>

            <!-- 设置在 getter 方法中,是否对 String 类型的字段调用 trim() 方法;默认为 false -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- SQL Map 的 xml 文件生成器 -->
        <sqlMapGenerator targetPackage="${package.sqlMapper}" targetProject="src/main/resources">
            <!-- 同 javaModelGenerator 元素中的配置  -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!--  关于 Mapper 接口的生成 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="${package.mapper}"
                             targetProject="src/main/java">
            <!-- 同 javaModelGenerator 元素中的配置  -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- 配置需要生成代码的数据库表 -->
        <!--        <table tableName="role" domainObjectName="Role"-->
        <!--               enableCountByExample="false" enableUpdateByExample="false"-->
        <!--               enableDeleteByExample="false" enableSelectByExample="false"-->
        <!--               selectByExampleQueryId="false">-->

        <!--            &lt;!&ndash; 指定是否只生成 domain 类,默认为 false;-->
        <!--            如果设置为 true,则只生成 domain 类,如果还配置了sqlMapGenerator,那么-->
        <!--            在 mapper.xml 文件中,只生成 resultMap 元素 &ndash;&gt;-->
        <!--            <property name="modelOnly" value="false"/>-->

        <!--            &lt;!&ndash; 默认为 false;如果设置为 true,生成的 model 类会直接使用 column 本身的名字,而不会再使用驼峰命名方法,-->
        <!--            比如 CREATE_DATE,生成的属性名字就是 CREATE_DATE,而不会是 createDate &ndash;&gt;-->
        <!--            <property name="useActualColumnNames" value="false"/>-->

        <!--            &lt;!&ndash;  生成主键的方法,如果设置了该元素,MBG 会在生成的 <insert> 元素中生成一条正确的 <selectKey> 元素 &ndash;&gt;-->
        <!--            <generatedKey column="id" sqlStatement="MySql" identity="true"/>-->

        <!--            &lt;!&ndash; 用来修改表中某个列的属性,MBG 会根据修改后的配置来生成 domain 的属性;-->
        <!--                column:要重新设置的列名;一个 table 元素中可以定义多个 columnOverride 元素哈 &ndash;&gt;-->
        <!--            <columnOverride column="show_status">-->
        <!--                &lt;!&ndash; 使用 property 属性来指定列要生成的属性名称 &ndash;&gt;-->
        <!--                <property name="property" value="showStatus"/>-->

        <!--                &lt;!&ndash; javaType 用于指定生成的 domain 的属性类型,使用类型的全限定名&ndash;&gt;-->
        <!--                <property name="javaType" value="java.lang.Integer"/>-->

        <!--                &lt;!&ndash; jdbcType用于指定该列的JDBC类型-->
        <!--                <property name="jdbcType" value=""/>-->
        <!--                 &ndash;&gt;-->
        <!--            </columnOverride>-->

        <!--        </table>-->



        <table tableName="user_account"  enableCountByExample="false">

        </table>
    </context>
</generatorConfiguration>

每个标签的具体含义可以参考博客:
Mybatis代码生成器Mybatis-Generator使用详解

三.运行

mvn mybatis-generator:generate

四. mybatis-generator 自定义生成的文件名

在根据表名生成实体类时,其类名和字段名默认使用驼峰命名,比方说 CREATE_DATE,生成的属性名字就是createDate
相关属性设置: <property name="useActualColumnNames" value="false"/>

但是表名有时候比较长,我们就想要自己定义生成的文件名。

一.domainObjectName和mapperName属性

比较简单的做法就是对每一个表名定义你想要的实体类名domainObjectName

比方说,由于业务需要你定义了持久化类(Persistent Object),业务类(Business Object),在不同使用场景想在持久化类加上对应的后缀,那么就可以使用domainObjectName

        <table tableName="t_user_account"  enableCountByExample="false" domainObjectName="UserAccountPo">

注意: domainObjectName 定义的名称会导致生成的Mapper类名和Example类名也发生变化,上述例子中会变为UserAccountPoMapper和UserAccountPoExample

如果不想让Mapper类名发生变化, 可以指定下Mapper类名

        <table tableName="t_user_account"  enableCountByExample="false"  mapperName="UserAccountMapper" domainObjectName="UserAccountPo">

此时生成的Mapper和Example类名为 UserAccountMapper和UserAccountPoExample

上述方式的缺点就是每个table都需要单独指定类名,比较繁琐

二.domainObjectRenamingRule标签

如果表名有统一的规则,我们只是想将表名的固定前缀去除,然后加上固定后缀,就可以使用domainObjectRenamingRule标签

<!-- 去除首字母t(之所以要忽略大小写是因为searchString是在table名称驼峰化之后修改的), 然后在剩余部分加上后缀Po-->
 <table tableName="t_user_account"  enableCountByExample="false" >
           <domainObjectRenamingRule searchString="(?i)^t(.*)" replaceString="$1Po"/>
 </table>

那么如果该表没有需要去除的前缀呢? 可以这样写

 <table tableName="user_account"  enableCountByExample="false" >
           <domainObjectRenamingRule searchString="(?i)^user(.*)" replaceString="User$1Po"/>
 </table>

三. RenameExampleClassPlugin插件

RenameExampleClassPlugin可以修改example文件名

<!--修改Example文件名-->
<plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">  
    <property name="searchString" value="Example$"/> 
    <property name="replaceString" value="Condition"/> 
</plugin>

四. columnRenamingRule标签

columnRenamingRule 可以修改实体属性名,其有两个属性: searchString,replaceString。用法跟domainObjectRenamingRule类似。注意 : 该标签的searchString 是在没有驼峰化之前生效的

  • 18
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值