当前位置: 首页 > news >正文

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

文章目录

  • Mybatis Generator自动化生成代码
    • MyBatis Generator概述
    • 使用Java代码形式
      • 1. 在 Maven 或 Gradle 中添加 MyBatis Generator 的依赖:
      • 2. 编写配置文件 GeneratorConfig.xml,配置需要生成的数据库表和对应的生成器:
      • 3. 在命令行中使用 MyBatis Generator 进行代码生成:
    • 使用Maven插件
      • pom.xml中添加依赖
      • pom.xml中build-plugins下添加插件
      • mybatis-generator-config.xml
      • 运行
  • MyBatis-Plus 的 AutoGenerator
    • MyBatis-Plus AutoGenerator概述
      • 1. 在 Maven 或 Gradle 中添加 MyBatis-Plus 的依赖:
      • 2. 配置数据源和 MyBatis-Plus 的相关配置:
      • 3. 编写配置文件 MybatisPlusConfig.java,配置自动生成代码的相关信息:
      • 4. 在启动类中调用 AutoGenerator 的 run 方法即可进行代码生成:
  • 两者对比
  • 总结

自动化生成代码是现在一种非常常见的技术,它可以大大提高开发效率,减少重复劳动。而在 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 generatorConfigurationPUBLIC "-//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-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 类型解析为 Integertrue:把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-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=UTCusername: rootpassword: rootdriver-class-name: com.mysql.jdbc.Drivermybatis-plus:mapper-locations: classpath:mapper/*.xmltype-aliases-package: com.example.pojoglobal-config:db-config:id-type: auto

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

@Configuration
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}@Beanpublic MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {return plusProperties -> plusProperties.getGlobalConfig().setBanner(false);}@Beanpublic 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 GeneratorMyBatis-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 两个自动化代码生成工具的使用方法和区别,它们可以大大提升开发效率,减少重复劳动。在实际开发中,我们可以根据项目的需求选择合适的工具进行使用。

相关文章:

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

文章目录 Mybatis Generator自动化生成代码MyBatis Generator概述使用Java代码形式1. 在 Maven 或 Gradle 中添加 MyBatis Generator 的依赖&#xff1a;2. 编写配置文件 GeneratorConfig.xml&#xff0c;配置需要生成的数据库表和对应的生成器&#xff1a;3. 在命令行中使用 M…...

达梦数据库-DW-国产化--九五小庞

武汉达梦数据库股份有限公司成立于2000年&#xff0c;是国内领先的数据库产品开发服务商&#xff0c;国内数据库基础软件产业发展的关键推动者。公司为客户提供各类数据库软件及集群软件、云计算与大数据等一系列数据库产品及相关技术服务&#xff0c;致力于成为国际顶尖的全栈…...

LeetCode 753. 破解保险箱【欧拉回路,DFS】困难

本文属于「征服LeetCode」系列文章之一&#xff0c;这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁&#xff0c;本系列将至少持续到刷完所有无锁题之日为止&#xff1b;由于LeetCode还在不断地创建新题&#xff0c;本系列的终止日期可能是永远。在这一系列刷题文章…...

深度学习概念(术语):Fine-tuning、Knowledge Distillation, etc

文章目录 1.Fine-tuning (微调)2.Transfer Learning (迁移学习)3.Knowledge Distillation (知识蒸馏)4.Meta Learning (元学习) 这里的相关概念都是基于已有预训练模型&#xff0c;就是模型本身已经训练好&#xff0c;有一定泛化能力。需要“再加工”满足别的任务需求。 进入后…...

tcp_v4_connect函数的解析

源码&#xff1a; int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) {// 解析输入的地址结构struct sockaddr_in *usin (struct sockaddr_in *)uaddr;// 获取 TCP 协议栈的全局 death_row 对象struct inet_timewait_death_row *tcp_death_row;// …...

go-channel

设计原理 Go 提及的设计模式就是&#xff1a;不要通过共享内存的方式进行通信&#xff0c;而是应该通过通信的方式共享内存。 共享内存方式&#xff1a;多个协程共享同一块内存&#xff0c;但是多个协程中读写变量是操作同一块内存&#xff0c;会产生多线程问题的并发问题&am…...

K8s操作命令

生命周期管理 1. 创建 1. 创建资源 kubectl run 创建并运行一个或多个容器镜像。*创建一个deployment或job来管理容器*。 语法&#xff1a;kubectl run NAME --imageimage [–env“keyvalue”] [–portport] [–replicasreplicas] [–dry-runbool] [–overridesinline-jso…...

【MySQL】 MySQL数据库基础

文章目录 &#x1f431;‍&#x1f453;数据库的操作&#x1f4cc;显示当前的数据库&#x1f4cc;创建数据库&#x1f388;语法&#xff1a;&#x1f388;语法说明&#x1f388;示例&#xff1a; &#x1f334;使用数据库&#x1f38b;删除数据库&#x1f431;‍&#x1f3cd;语…...

vscode 下载安装

vscode 下载安装常用插件 vscode 官网&#xff1a; https://code.visualstudio.com/ 点击右上角 Download 进入下载选择页面 选择自己使用操作对应 CPU 架构 下载 本文使用 x86 架构 64位 windows 系统为例 跳转下载页面 自动 开始下载 下载不开始&#xff1f;试试这个直…...

springboot对接postgres

安装postgres 注意:下述链接方式会自动创建数据库steven_russell,若需要创建其他数据库&#xff0c;可以手动执行命令创建数据库 docker run --name postgres \ -p 5432:5432 \ -e POSTGRES_USERsteven_russell \ -e POSTGRES_PASSWORD123456 \ -itd --privilegedtrue postgre…...

[python 刷题] 242 Valid Anagram

[python 刷题] 242 Valid Anagram 题目&#xff1a; Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the o…...

算法通过村第七关-树(递归/二叉树遍历)青铜笔记|手撕递归

文章目录 前言1. 递归的特征2. 如何写出好的递归3. 怎么看懂递归的代码总结 前言 提示&#xff1a;我们生活在24小时不眠不休的社会里但是没有24小时不眠不休的身体有些东西必须舍弃 -- 马特海格 这一关&#xff0c;我看要谈论的是递归问题&#xff0c;说到它就牵扯到很多问题了…...

#循循渐进学51单片机#点亮你的LED#not.2

1、深刻理解电容的意义&#xff0c;并且在今后的电路学习过程中要多多注意参考别人电路中去耦电路的处理方法&#xff0c;积累经验。 1&#xff09;电容缓冲电压&#xff0c;抗电磁干扰&#xff1b; 2&#xff09;低频率电容&#xff0c;一般用的最多的是钽电容&#xff0c;电…...

基于Java+SpringBoot+Vue+uniapp点餐小程序(亮点:协同过滤算法、会员系统,购物车结算、在线聊天)

校园点餐小程序 一、前言二、我的优势2.1 自己的网站2.2 自己的小程序&#xff08;小蔡coding&#xff09;2.3 有保障的售后2.4 福利 三、开发环境与技术3.1 MySQL数据库3.2 Vue前端技术3.3 Spring Boot框架3.4 微信小程序 四、功能设计4.1 系统功能结构设计4.2 主要功能描述 五…...

深度学习-全连接神经网络-详解梯度下降从BGD到ADAM - [北邮鲁鹏]

文章目录 参考文章及视频导言梯度下降的原理、过程一、什么是梯度下降&#xff1f;二、梯度下降的运行过程 批量梯度下降法(BGD)随机梯度下降法(SGD)小批量梯度下降法(MBGD)梯度算法的改进梯度下降算法存在的问题动量法(Momentum)目标改进思想为什么有效动量法还有什么效果&…...

数据结构--二叉排序树

目录 二叉排序树的定义 二叉排序树的查找 二叉排序树的插入 二叉排序树的构造 二叉排序树的删除 查找效率分析 回顾 二叉排序树的定义 二叉排序树的查找 查找成功的情况 查找失败的情况 二叉排序树的插入 注意 &#xff08;1&#xff09;二叉排序树不允许出现重复的值…...

Python | 根据子列表中的第二个元素对列表进行排序

在本文中&#xff0c;我们将学习如何根据主列表中存在的子列表的第二个元素对任何列表进行排序。 比如 Input : [[‘rishav’, 10], [‘akash’, 5], [‘ram’, 20], [‘gaurav’, 15]] Output : [[‘akash’, 5], [‘rishav’, 10], [‘gaurav’, 15], [‘ram’, 20]] Input …...

qsort函数详细讲解以及利用冒泡排序模拟实现qsort函数

个人主页&#xff1a;点我进入主页 专栏分类&#xff1a;C语言初阶 C语言程序设计————KTV C语言小游戏 C语言进阶 C语言刷题 欢迎大家点赞&#xff0c;评论&#xff0c;收藏。 一起努力&#xff0c;一起奔赴大厂。 目录 1.qsort函数 1.1qsort函数的参数 …...

C++QT day6

1> 将之前定义的栈类和队列类都实现成模板类 栈&#xff1a; #include <iostream> #define MAX 128 using namespace std; template<typename T> class Stack_s { private:T *pnew T[MAX];//栈的数组int top;//记录栈顶的变量 public://构造函数Stack_s(int t…...

List与ArrayList

目录 一、List及其使用 1.1 List的概念 1.2 常见接口的介绍 1.3 List的使用 二、线性表和顺序表 2.1 线性表 2.2 顺序表 三、ArrayList介绍 四、ArrayList的使用 4.1 ArrayList构造 4.2 ArrayList的常用方法 4.3 ArrayList的遍历 4.4 ArrayList的扩容机制 五、ArrayList的具…...

浏览器访问 AWS ECS 上部署的 Docker 容器(监听 80 端口)

✅ 一、ECS 服务配置 Dockerfile 确保监听 80 端口 EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]或 EXPOSE 80 CMD ["python3", "-m", "http.server", "80"]任务定义&#xff08;Task Definition&…...

Linux简单的操作

ls ls 查看当前目录 ll 查看详细内容 ls -a 查看所有的内容 ls --help 查看方法文档 pwd pwd 查看当前路径 cd cd 转路径 cd .. 转上一级路径 cd 名 转换路径 …...

ServerTrust 并非唯一

NSURLAuthenticationMethodServerTrust 只是 authenticationMethod 的冰山一角 要理解 NSURLAuthenticationMethodServerTrust, 首先要明白它只是 authenticationMethod 的选项之一, 并非唯一 1 先厘清概念 点说明authenticationMethodURLAuthenticationChallenge.protectionS…...

算法笔记2

1.字符串拼接最好用StringBuilder&#xff0c;不用String 2.创建List<>类型的数组并创建内存 List arr[] new ArrayList[26]; Arrays.setAll(arr, i -> new ArrayList<>()); 3.去掉首尾空格...

听写流程自动化实践,轻量级教育辅助

随着智能教育工具的发展&#xff0c;越来越多的传统学习方式正在被数字化、自动化所优化。听写作为语文、英语等学科中重要的基础训练形式&#xff0c;也迎来了更高效的解决方案。 这是一款轻量但功能强大的听写辅助工具。它是基于本地词库与可选在线语音引擎构建&#xff0c;…...

Java + Spring Boot + Mybatis 实现批量插入

在 Java 中使用 Spring Boot 和 MyBatis 实现批量插入可以通过以下步骤完成。这里提供两种常用方法&#xff1a;使用 MyBatis 的 <foreach> 标签和批处理模式&#xff08;ExecutorType.BATCH&#xff09;。 方法一&#xff1a;使用 XML 的 <foreach> 标签&#xff…...

pikachu靶场通关笔记19 SQL注入02-字符型注入(GET)

目录 一、SQL注入 二、字符型SQL注入 三、字符型注入与数字型注入 四、源码分析 五、渗透实战 1、渗透准备 2、SQL注入探测 &#xff08;1&#xff09;输入单引号 &#xff08;2&#xff09;万能注入语句 3、获取回显列orderby 4、获取数据库名database 5、获取表名…...

Monorepo架构: Nx Cloud 扩展能力与缓存加速

借助 Nx Cloud 实现项目协同与加速构建 1 &#xff09; 缓存工作原理分析 在了解了本地缓存和远程缓存之后&#xff0c;我们来探究缓存是如何工作的。以计算文件的哈希串为例&#xff0c;若后续运行任务时文件哈希串未变&#xff0c;系统会直接使用对应的输出和制品文件。 2 …...

JDK 17 序列化是怎么回事

如何序列化&#xff1f;其实很简单&#xff0c;就是根据每个类型&#xff0c;用工厂类调用。逐个完成。 没什么漂亮的代码&#xff0c;只有有效、稳定的代码。 代码中调用toJson toJson 代码 mapper.writeValueAsString ObjectMapper DefaultSerializerProvider 一堆实…...

李沐--动手学深度学习--GRU

1.GRU从零开始实现 #9.1.2GRU从零开始实现 import torch from torch import nn from d2l import torch as d2l#首先读取 8.5节中使用的时间机器数据集 batch_size,num_steps 32,35 train_iter,vocab d2l.load_data_time_machine(batch_size,num_steps) #初始化模型参数 def …...