MyBatis-Plus08:代码生成

MyBatis-Plus 常用代码生成器

MyBatis-Plus 常用的代码生成器主要有以下 3 种

生成器 类型 适用场景 推荐度
AutoGenerator 编程式(Java代码) 灵活定制,适合大多数项目 ⭐⭐⭐⭐⭐
mybatis-plus 插件 可视化界面 快速生成,适合新手 ⭐⭐⭐⭐
MyBatisX 插件 IDEA 插件 单表快速生成,最方便 ⭐⭐⭐⭐⭐

一、AutoGenerator(官方推荐)

这是 MyBatis-Plus 官方提供的代码生成器,通过 Java 代码配置生成。

1-1、添加依赖

1-2、快速使用示例

java 复制代码
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;

import java.util.Collections;

public class CodeGenerator {
    public static void main(String[] args) {
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/your_db?useSSL=false&serverTimezone=UTC", 
                "root", "your_password")
            .globalConfig(builder -> {
                builder.author("your_name") // 设置作者
                    .outputDir("src/main/java"); // 输出目录
            })
            .packageConfig(builder -> {
                builder.parent("com.example.wsmybatisplus") // 父包名
                    .entity("entity")
                    .mapper("mapper")
                    .service("service")
                    .serviceImpl("service.impl")
                    .controller("controller")
                    .pathInfo(Collections.singletonMap(OutputFile.xml, "src/main/resources/mapper"));
            })
            .strategyConfig(builder -> {
                builder.addInclude("user", "order", "product") // 指定生成的表
                    .addTablePrefix("t_"); // 移除表前缀
            })
            .execute();
    }
}

详细可见mybatis-plus的官网。

1-3、优点

  • 灵活可定制
  • 可批量生成多表
  • 支持自定义模板

1-4、缺点

  • 需要写 Java 代码配置
  • 每次修改配置要重新运行

二、插件一:MybatisPlus

2-1、使用方法


三、MyBatisX 插件(IDEA 插件)⭐ 最推荐

这是 IntelliJ IDEA 官方插件,集成在 IDE 中,使用最方便!

3-1、安装步骤

  1. 打开 IDEA → Settings → Plugins
  2. 搜索 MyBatisX
  3. 点击 Install → 重启 IDEA

3-2、使用方法

安装完成后我们会发现所有的Mapper接口和mapper.xml文件都变成了MyBatis的小鸟图标。

XML与接口互跳

点击Mapper接口方法左侧的图标可以直接跳转到mapper.xml对应的SQL实现,在mapper.xml点击左侧图标也可以直接跳转到Mapper接口中对应的方法。

(可以是实现Mapper跳转到对应方法中的功能)

自动生成代码

MyBatisX直接整了个带图形化界面的,下面我们来体验下。

选中表以后右键可以直接生成对应表的CRUD代码,当然你也可以多选,支持一次性生成多表;

填写module path, package path等信息

【注意】:

module path就用默认带过来的就行!

相关推荐
ruleslol3 小时前
MyBatis-Plus09:静态工具Db
mybatis-plus
树码小子7 小时前
Mybatis(17)Mybatis-Plus条件构造器(2)& 自定义 SQL
数据库·sql·mybatis-plus
ruleslol8 小时前
MyBatis-Plus10:逻辑删除
mybatis-plus
树码小子1 天前
Mybatis(16)Mybatis-Plus条件构造器(1)
数据库·mybatis-plus
树码小子2 天前
Mybatis(14)Mybatis-Plus入门 & 简单使用
java·mybatis-plus
ruleslol3 天前
MyBatis-Plus06:IService接口Lambda基本用法
mybatis-plus
ruleslol4 天前
MyBatis-Plus02: 常用注解
mybatis-plus
ruleslol6 天前
MyBatis-Plus05:IService接口基本用法
mybatis-plus
ruleslol6 天前
MyBatis-Plus04:自定义SQL
mybatis-plus