MyBatisPlus 最新版代码生成器(直接拿来就能用,包含自动生成 Vue 模版)

本文涉及的产品
云原生数据库 PolarDB MySQL 版,Serverless 5000PCU 100GB
简介: MyBatisPlus 最新版代码生成器(直接拿来就能用,包含自动生成 Vue 模版)

开始了喂~

别眨眼 O,O

一、编辑 pom.xml 文件,添加依赖

注意:

  • 数据库,我用的是 PostgreSQL,用 MySQL 的同学记得自己换哈~
  • 模版,我用的是 FreeMarker,用 Velocity 的同学记得自己换哈~
<properties>
    <java.version>18</java.version>
      <postgresql.version>42.3.6</postgresql.version>
      <druid.version>1.2.10</druid.version>
      <mybatis-plus.version>3.5.1</mybatis-plus.version>
      <mybatis-plus-generator.version>3.5.2</mybatis-plus-generator.version>
      <freemarker.version>2.3.31</freemarker.version>
  </properties>
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 数据库相关 -->
        <!-- postgresql 数据库连接驱动 -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>${postgresql.version}</version>
        </dependency>
        <!-- druid 数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>
        <!-- mybatis-plus 自动生成代码模块 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>${mybatis-plus-generator.version}</version>
        </dependency>
        <!-- FreeMarker 模板引擎 -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>${freemarker.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

二、编辑 application.properties 文件

# SpringBoot 启动端口
server.port=9999
# 数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.username=hello
spring.datasource.password=hello1234
spring.datasource.url=jdbc:postgresql://localhost:5432/auto_trader
# 日志存放位置
logging.file.name=./log/hello.txt
# 日志的等级
# com.hello 是你的包路径
logging.level.com.hello=debug
#作者
code.generated.author=hello
#//待生成对象表名
code.generated.table-name=你的数据表名,多张表用逗号隔开

三、创建「代码自动生成器」类:AutoCodeGenerator

我在 src/main/java/ 目录下,创建了一个 AutoCodeGenerator 文件。

你看,它要导入巨多的包(不过,这些都是自动导入的,我就是想凑字数,贴出来给你看看)

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer;

具体代码也无敌多,建议:逐字逐句阅读,尽可能一次性搞懂,加油!

public class AutoCodeGenerator {
    private static String driverClassName;  // 驱动名称
    private static String username;  // 数据库用户名
    private static String password;  // 数据库用户密码
    private static String url;  // 数据库连接URL
    private static String author;  // 作者
    private static String tableName;  // 待生成对象表名
    /**
     * 读取 application.properties 配置文件
     */
    private static void readProperty() throws IOException {
        Properties properties = new Properties();
        // 读取文件并转换编码为 UTF-8,解决 application.properties 配置文件中文乱码
        InputStreamReader inputStreamReader = new InputStreamReader(Objects.requireNonNull(AutoCodeGenerator.class.getClassLoader().getResourceAsStream("application.properties")), StandardCharsets.UTF_8);
        properties.load(inputStreamReader);
        driverClassName = properties.getProperty("spring.datasource.driver-class-name");
        username = properties.getProperty("spring.datasource.username");
        password = properties.getProperty("spring.datasource.password");
        url = properties.getProperty("spring.datasource.url");
        author = properties.getProperty("code.generated.author");
        tableName = properties.getProperty("code.generated.table-name");
    }
    /**
     * MyBatis-Plus 代码生成器「新」
     * 适用版本:mybatis-plus-generator 3.5.1 及其以上版本,对历史版本不兼容
     * 执行 run
     */
    public static void main(String[] args) throws Exception {
        // 加载数据库配置
        readProperty();
        // 项目路径
        String projectPath = System.getProperty("user.dir");
        // 根据数据源信息,创建文件,生成代码
        FastAutoGenerator.create(new DataSourceConfig.Builder(url,username,password))
                // 全局配置
                .globalConfig(builder -> builder
                        // 作者
                        .author(author)
                        // 输出路径
                        .outputDir(projectPath + "/target/generated-sources")
                        .dateType(DateType.TIME_PACK))
                // 包配置
                .packageConfig(builder -> builder
                        // 指定父包名
                        .parent("com.hello")
                        .entity("entities")
                        .service("services")
                        .serviceImpl("services.impl")
                        .mapper("mapper")
                        .controller("models"))
                // 模版配置
                .templateConfig(builder -> builder
                        .entity("/templates/entity.java")
                        .service("/templates/service.java")
                        .serviceImpl("/templates/serviceImpl.java")
                        .mapper("/templates/mapper.java")
                        .controller("/templates/controller.java"))
                // 策略配置
                .strategyConfig(builder -> builder
                        // 指定表名,用逗号分隔
                        .addInclude(tableName.split(","))
                        // 先开启 Controller 配置
                        .controllerBuilder()
                        // 开启生成 @RestController 控制器
                        .enableRestStyle()
                        // 开启驼峰转连字符
                        .enableHyphenStyle()
                        // 先开启 Entity 配置
                        .entityBuilder()
                        // 开启主键自增
                        .idType(IdType.AUTO)
                        // 数据库表映射到实体的命名策略,驼峰命名
                        .naming(NamingStrategy.underline_to_camel)
                        // 数据库表字段映射到实体的命名策略,驼峰命名
                        .columnNaming(NamingStrategy.underline_to_camel)
                        // 开启生成实体时生成字段注解
                        .enableTableFieldAnnotation())
                // 自定义配置:用来生产前端部分的 Vue 页面
                .injectionConfig(consumer -> {
                    Map<String, String> customFile = new HashMap<>();
                    // 根据指定的模版,生成对应的文件
                    customFile.put("aaa.vue", "/templates/aaa.vue.ftl");
                    customFile.put("bbb.vue", "/templates/bbb.vue.ftl");
                    consumer.customFile(customFile);
                })
                // freemarker 模版
                .templateEngine(new FreemarkerTemplateEngine(){
                    @Override
                    protected void outputCustomFile(@NotNull Map<String, String> customFile, @NotNull TableInfo tableInfo, @NotNull Map<String, Object> objectMap) {
                      //存放取出的实体名称,用于生成路由
                        List<String> entityNames = new ArrayList<>();
                        if (!entityNames.contains(tableInfo.getEntityName())){
                            entityNames.add(tableInfo.getEntityName());
                        }
                        customFile.forEach((key, value) -> {
                            String fileName = String.format(projectPath + "/src/main/resources/static/" + tableInfo.getEntityName() + File.separator + tableInfo.getEntityName() +   "%s", key);
                            this.outputFile(new File(fileName), objectMap, value, this.getConfigBuilder().getInjectionConfig().isFileOverride());
                        });
                        // 生成路由部分
                        Map<String, Object> routers = new HashMap<>();
                        routers.put("author", author);
                        routers.put("date", new Date());
                        routers.put("entities", entityNames);
                        
                        // 使用 freemarker 模板引擎,路由页面路径
                        String templateRoutesPath = "/templates/routes_generated.js.ftl";
                        
                        // 生成的路由页面路径
                        File templateRoutesOutFile = new File(projectPath + "/src/main/resources/static/routes_generated.js");
                        try {
                            this.writer(routers, templateRoutesPath, templateRoutesOutFile);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                })
                // 执行
                .execute();
    }
}

搞定啦!是不是很简单?请各位老板,加个关注,点个赞呗!

以后天天来,把开发中的好源码,都分享出来~

相关实践学习
使用PolarDB和ECS搭建门户网站
本场景主要介绍基于PolarDB和ECS实现搭建门户网站。
阿里云数据库产品家族及特性
阿里云智能数据库产品团队一直致力于不断健全产品体系,提升产品性能,打磨产品功能,从而帮助客户实现更加极致的弹性能力、具备更强的扩展能力、并利用云设施进一步降低企业成本。以云原生+分布式为核心技术抓手,打造以自研的在线事务型(OLTP)数据库Polar DB和在线分析型(OLAP)数据库Analytic DB为代表的新一代企业级云原生数据库产品体系, 结合NoSQL数据库、数据库生态工具、云原生智能化数据库管控平台,为阿里巴巴经济体以及各个行业的企业客户和开发者提供从公共云到混合云再到私有云的完整解决方案,提供基于云基础设施进行数据从处理、到存储、再到计算与分析的一体化解决方案。本节课带你了解阿里云数据库产品家族及特性。
目录
相关文章
|
7月前
|
自然语言处理 JavaScript
【Vue2.0源码学习】模板编译篇-模板解析(代码生成阶段)
【Vue2.0源码学习】模板编译篇-模板解析(代码生成阶段)
36 0
|
10月前
|
JavaScript
若依代码生成自带导入功能
若依代码生成自带导入功能
327 0
|
安全 API CDN
搭建Vue3组件库:第十五章 如何编写README文档
本章介绍如何正确编写项目的README文档
536 0
搭建Vue3组件库:第十五章 如何编写README文档
|
设计模式 资源调度 JavaScript
vue脚手架基础API全面讲解【内附多个案例】
vue脚手架基础API全面讲解【内附多个案例】
vue脚手架基础API全面讲解【内附多个案例】
|
JavaScript
搭建Vue3组件库:第四章 使用Vitepress搭建文档网站
文档建设一般会是一个静态网站的形式 ,这次采用 Vitepress 完成文档建设工作。 Vitepress 是一款基于Vite 的静态站点生成工具。开发的初衷就是为了建设 Vue 的文档。Vitepress 的方便之处在于,可以使用流行的 Markdown 语法进行编写,也可以直接运行 Vue 的代码。也就是说,它能很方便地完成展示组件 Demo 的任务。
1323 0
搭建Vue3组件库:第四章 使用Vitepress搭建文档网站
|
5月前
|
JavaScript
Vue项目常见的文档导入调接口
Vue项目常见的文档导入调接口
|
10月前
|
存储 JavaScript 前端开发
【开发模板】Vue和SpringBoot的前后端分离开发模板(二)
【开发模板】Vue和SpringBoot的前后端分离开发模板
|
10月前
|
JavaScript 前端开发 NoSQL
【开发模板】Vue和SpringBoot的前后端分离开发模板(一)
【开发模板】Vue和SpringBoot的前后端分离开发模板
128 0
|
10月前
|
JavaScript 前端开发 Java
【开发模板】Vue和SpringBoot的前后端分离开发模板(三)
【开发模板】Vue和SpringBoot的前后端分离开发模板
|
11月前
|
前端开发 JavaScript
从0搭建Vue3组件库(五): 如何使用Vite打包组件库
从0搭建Vue3组件库(五): 如何使用Vite打包组件库
600 0