自动化生成代码:MyBatis 的 Generator与MyBatis-Plus 的 AutoGenerator

这篇具有很好参考价值的文章主要介绍了自动化生成代码:MyBatis 的 Generator与MyBatis-Plus 的 AutoGenerator。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

自动化生成代码是现在一种非常常见的技术,它可以大大提高开发效率,减少重复劳动。而在 Java 开发中,MyBatis 是一个非常流行的 ORM 框架,而其中的 Generator 和 MyBatis-Plus 中的 AutoGenerator 是两个非常好用的自动化代码生成工具,下面我们来分别介绍一下它们的使用。

Mybatis Generator自动化生成代码

MyBatis Generator概述

MyBatis Generator 是 MyBatis 框架提供的一个自动生成代码的工具,它能够根据数据库中的表自动生成对应的 POJO、Mapper 接口和 XML 配置文件,同时也支持自定义插件的开发。使用 MyBatis Generator 的步骤如下:

使用Java代码形式

1. 在 Maven 或 Gradle 中添加 MyBatis Generator 的依赖:

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

2. 编写配置文件 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>
    <context id="testTables" targetRuntime="MyBatis3">
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

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

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

        <javaModelGenerator targetPackage="com.example.pojo"
            targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="com.example.mapper"
            targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.example.mapper"
            targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <table tableName="tb_user" domainObjectName="User"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false" />

    </context>
</generatorConfiguration>

3. 在命令行中使用 MyBatis Generator 进行代码生成:

java -jar mybatis-generator-core-1.4.0.jar -configfile GeneratorConfig.xml -overwrite

这样就会在指定的包路径和项目路径下生成对应的 POJO、Mapper 接口和 XML 配置文件。但编写代码还需要配置一些信息,也挺麻烦哈,偷个懒吧再,使用Maven 插件帮咱们干活。

使用Maven插件

pom.xml中添加依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

pom.xml中build-plugins下添加插件

添加了插件后,我们使用 configurationFile 元素来指定一个配置文件 mybatis-generator-config.xml
而且数据库表可能会发生变动,因此我们需要追加一个配置 <overwrite>true</overwrite>,允许覆盖旧的文件。为了防止我们编写的 SQL 语句被覆盖掉,MyBatis Generator 只会覆盖旧的 po、dao、而 *mapper.xml 不会覆盖,而是追加。

<!-- MyBatis Generator 插件 -->
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.7</version>
    <configuration>
        <!-- MyBatis Generator 生成器的配置文件-->
        <configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
        <!-- 允许覆盖生成的文件,确定骨架代码后就可以设为 false 了,免得覆盖原有代码 -->
        <overwrite>true</overwrite>
        <!-- 将当前 pom 的依赖项添加到生成器的类路径中-->
        <includeCompileDependencies>true</includeCompileDependencies>
    </configuration>
</plugin>

结构如下图:
mybatis 代码自动生成,Mybatis,自动化,mybatis

mybatis-generator-config.xml

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

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

        <!-- jdbc连接 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai&amp;useSSL=false"
                        userId="root"
                        password="1234">
        </jdbcConnection>

        <!-- 类型转换 -->
        <javaTypeResolver>
            <!--是否使用bigDecimal,默认false。
                false:把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer
                true:把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal-->
            <property name="forceBigDecimals" value="true"/>
        </javaTypeResolver>

        <!-- 生成实体类地址 -->
        <javaModelGenerator targetPackage="com.example.pojo" targetProject="src/main/java">
            <!-- 是否针对string类型的字段在set方法中进行修剪,默认false -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>


        <!-- 生成Mapper.xml文件 -->
        <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/resources">
        </sqlMapGenerator>

        <!-- 生成 XxxMapper.java 接口-->
        <javaClientGenerator targetPackage="com.example.mapper" targetProject="src/main/java" type="XMLMAPPER">
        <property name="enableSubPackages" value="true" />
        </javaClientGenerator>


        <!-- schema为数据库名,oracle需要配置,mysql不需要配置。
             tableName为对应的数据库表名
             domainObjectName 是要生成的实体类名(可以不指定,默认按帕斯卡命名法将表名转换成类名)
             enableXXXByExample 默认为 true, 为 true 会生成一个对应Example帮助类,帮助你进行条件查询,不想要可以设为false
             -->
        <table schema="" tableName="posts" domainObjectName="Posts"
               enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false" selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

运行

mybatis 代码自动生成,Mybatis,自动化,mybatis

MyBatis-Plus 的 AutoGenerator

MyBatis-Plus AutoGenerator概述

MyBatis-Plus 是在 MyBatis 的基础上扩展了一些功能的框架,其中 AutoGenerator 就是 MyBatis-Plus 提供的自动生成代码的工具,它能够一键生成对应的 POJO、Mapper 接口和 XML 配置文件,并且还支持模板引擎的自定义。

使用 MyBatis-Plus AutoGenerator 的步骤如下:

1. 在 Maven 或 Gradle 中添加 MyBatis-Plus 的依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.3.1</version>
</dependency>

2. 配置数据源和 MyBatis-Plus 的相关配置:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.pojo
  global-config:
    db-config:
      id-type: auto

3. 编写配置文件 MybatisPlusConfig.java,配置自动生成代码的相关信息:

@Configuration
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {
        return plusProperties -> plusProperties.getGlobalConfig().setBanner(false);
    }

    @Bean
    public AutoGenerator autoGenerator(DataSource dataSource) {
        AutoGenerator autoGenerator = new AutoGenerator();
        autoGenerator.setDataSource(dataSource);

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
        globalConfig.setAuthor("mybatis-plus");
        globalConfig.setFileOverride(true);
        globalConfig.setOpen(false);
        globalConfig.setEntityName("%sDO");
        autoGenerator.setGlobalConfig(globalConfig);

        // 数据库表配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setEntityLombokModel(true);
        strategyConfig.setRestControllerStyle(true);
        strategyConfig.setControllerMappingHyphenStyle(true);
        strategyConfig.setInclude("tb_user");

        // 包配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.example");
        packageConfig.setEntity("pojo");
        packageConfig.setMapper("mapper");
        packageConfig.setXml("mapper");

        // 模板引擎配置
        TemplateConfig templateConfig = new TemplateConfig();

        // 自定义模板配置,可以根据自己的需求进行修改
        templateConfig.setService("/templates/service.vm");
        templateConfig.setServiceImpl("/templates/serviceImpl.vm");
        templateConfig.setEntity("/templates/entity.vm");
        templateConfig.setMapper("/templates/mapper.vm");
        templateConfig.setXml("/templates/mapperXml.vm");

        autoGenerator.setTemplate(templateConfig);
        autoGenerator.setPackageInfo(packageConfig);
        autoGenerator.setStrategy(strategyConfig);

        return autoGenerator;
    }
}

4. 在启动类中调用 AutoGenerator 的 run 方法即可进行代码生成:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

        AutoGenerator autoGenerator = (AutoGenerator) ApplicationContextUtils.getBean("autoGenerator");
        autoGenerator.execute();
    }
}

这样就可以在指定的包路径和项目路径下生成对应的 POJO、Mapper 接口和 XML 配置文件。

两者对比

维度 MyBatis Generator MyBatis-Plus AutoGenerator
依赖配置 需要添加 MyBatis Generator 的单独依赖 需要添加 MyBatis-Plus 的整体依赖
配置文件 需要编写 GeneratorConfig.xml 配置文件 不需要额外的配置文件
支持数据库 支持主流的关系型数据库(如 MySQL、Oracle 等) 支持主流的关系型数据库(如 MySQL、Oracle 等)
可生成内容 POJO、Mapper 接口和 XML 配置文件 POJO、Mapper 接口和 XML 配置文件
插件支持 支持自定义插件开发 支持使用 MyBatis-Plus 内置的插件
模板引擎支持 不支持模板引擎 支持使用模板引擎进行自定义
配置灵活性 配置项较多,灵活度高 配置项较少,但使用起来更加简便
兼容性 对于 MyBatis 的版本兼容性较好 需要与 MyBatis-Plus 版本配套使用
社区支持和文档资料数 社区支持较好,文档资料丰富 社区支持较好,但文档资料数目相对较少

综上所述,MyBatis Generator 和 MyBatis-Plus AutoGenerator 都是非常好用的自动化代码生成工具,根据项目需求的不同,我们可以选择适合自己的工具来进行开发。MyBatis Generator 配置灵活度较高,可以根据需要进行自定义插件的开发,但需要编写较多的配置文件,而 MyBatis-Plus AutoGenerator 则更加简便,支持模板引擎的自定义,但配置项较少。

总结

以上就是 MyBatis Generator 和 MyBatis-Plus AutoGenerator 两个自动化代码生成工具的使用方法和区别,它们可以大大提升开发效率,减少重复劳动。在实际开发中,我们可以根据项目的需求选择合适的工具进行使用。文章来源地址https://www.toymoban.com/news/detail-774317.html

到了这里,关于自动化生成代码:MyBatis 的 Generator与MyBatis-Plus 的 AutoGenerator的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【重要】springboot实战(六)之mybatis-plus代码自动生成器

    目录 环境: 步骤: 1.添加依赖 2.配置代码 3.运行 测试 1.测试生成的service 1.1、service用法 2.分页查询 2.1、分页插件配置  2.2、测试 3.源码 jdk:1.8 springboot版本:2.7.15 mybatis-plus版本:3.5.1以上 (本文章用的当前最新版本:3.5.3.2,代码适用于3.5.1版本以上的版本) 在测试类中创建

    2024年02月03日
    浏览(35)
  • 【企业级SpringBoot单体项目模板 】——Mybatis-plus自动代码生成

    😜 作           者 :是江迪呀 ✒️ 本文 : SpringBoot项目模版 、 企业级 、 模版 ☀️ 每日   一言 : 我们之所以这样认为,是因为他们这样说。他们之所以那样说,是因为他们想让我们那样认为。所以实践才是检验真理的唯一准则。 上回 我们说了一些开发规范

    2024年02月07日
    浏览(32)
  • Mybatis三剑客(一)在springboot中自动生成Mybatis【generator】

    1、pom.xml中新增plugin 2、新建resources/generatorConfig.xml 注意:         context 中内容是有顺序的         commentGenerator在前面s 3、idea中的terminal中执行mybatis自动生成命令  mvn mybatis-generator:generate

    2024年02月12日
    浏览(29)
  • Mybatis generator实战:自动生成POJO类完整解决方案

    在用Mybatis generator 生成可以用来访问(多个)表的基础对象,遇到一个问题,就是columnRenamingRule可以替换所有表元素里字段前缀 但是如果想去掉所有表的前缀,比如有多个表: 期望得到的POJO结果是: 参照: https://github.com/mybatis/generator/issues/275 https://github.com/mybatis/generator/

    2024年02月04日
    浏览(26)
  • 代码生成器-mybatis-plus-generator

    我们平时在开发的过程中,对于新建的一张表难免会有对其进行增删改查的操作,而且还要写Controller、service、Mapper、Mapper.xml、PO、VO等等。如果每次都要去写这些跟业务毫不相干但是却又耗时耗力的重复代码这不仅是让开发人员不能专注于业务逻辑甚至可能由于不注意导致字

    2023年04月25日
    浏览(34)
  • 5.6 Mybatis代码生成器Mybatis Generator (MBG)实战详解

    本文我们主要实战Mybatis官方的代码生成器:Mybatis Generator(MBG),掌握它以后,可以简化大部分手写代码,我们只需要写复杂逻辑代码! 通过前几篇,我们掌握了在SpringBoot下Mybatis的基本用法,操作步骤回顾一下: 创建与MySQL表对应的Java PO对象,字段一一对应; 创建Mapper接口,

    2024年02月05日
    浏览(30)
  • 【sgCreateAPI】自定义小工具:敏捷开发→自动化生成API接口脚本(接口代码生成工具)

      具体步骤:登录 Apifox https://app.apifox.com/   圈选复制上面的内容粘贴到【接口地址列表】输入框,自动生成脚本代码 生成的接口请求代码是基于 【Vue.js最新版】【基于jQuery Ajax】[sd.js]最新原生完整版for凯哥API版本_你挚爱的强哥的博客-CSDN博客 【代码】【最新版】【基于j

    2024年02月09日
    浏览(39)
  • mybatis-generator代码生成器的使用与配置

    官网的MyBatis Generator使用介绍,请点击下面的链接: 链接 MyBatis Generator 生成的文件包含三类: (1)Model实体文件,一个数据库表对应生成一个 Model 实体; (2)Mapper接口文件,数据数操作方法都在此接口中定义; (3)Mapper XML配置文件 在pom.xml文件添加如下依赖: 代码如下

    2024年02月14日
    浏览(29)
  • springboot+maven插件调用mybatis generator自动生成对应的mybatis.xml文件和java类

    mybatis最繁琐的事就是sql语句和实体类,sql语句写在java文件里很难看,字段多的表一开始写感觉阻力很大,没有耐心,自动生成便成了最称心的做法。自动生成xml文件,dao接口,实体类,虽一直感觉不太优雅,但省去了很多麻烦,当表增加或修改字段的时候重新生成便轻松搞

    2024年02月14日
    浏览(28)
  • springboot的代码生成器mybatis-plus-generator-ui

    GeberatorUIServer 在springboot的test中运行 这段代码是一个用于生成 MyBatis-Plus 代码的工具类,进行解释: 这是一个名为 GeberatorUIServer 的类。 这是程序的入口方法,即 main 方法。 这段代码创建了一个 GeneratorConfig 对象,并使用链式调用的方式设置了一系列参数: jdbcUrl :数据库连

    2024年02月10日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包