springboot 集成mybatis plus 代码生成器

172 阅读2分钟

原因

完成上篇springBoot+mybatis plus+redis 项目搭建流程 想继续集成安全框架但是发现要写的重复代码比较多,所以这里先集成代码生成功能,减少重复工作量,自己以前也没弄过所以想试试.

导入需要用的jar包

<!-- mybatis plus 代码生成依赖 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.3</version>
</dependency>

<!-- 代码生成引擎模板依赖-->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
</dependency>

这里我用的是3.5.3的版本,目前mybatis-plus官网对generator 3.5.1 及其以上版本进行了重新设计,3.5.1及以上的版本更加容易使用;官方支持多种引擎依赖,默认的是velocity,同时工作中velocity也用的比较多所以就引入了这个依赖

编写代码生成调用逻辑

package com.wen.wealth.web.controller;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
/**
 * @ClassName GeneratorController
 * @Description 代码生成
 * @Author wen
 * @Date 2023/2/13 上午 11:45
 */
@RestController
@RequestMapping("/generator")
public class GeneratorController {

    @Value("${spring.datasource.druid.url}")
    private String url ;

    @Value("${spring.datasource.druid.username}")
    private String userName ;

    @Value("${spring.datasource.druid.password}")
    private String password ;

    /**
     * 生成新的代码
     */
    @GetMapping("/production")
    public void production(String tableName) throws Exception {

        FastAutoGenerator.create(url, userName, password)
                .globalConfig(builder -> {
                    builder.author("wen") // 设置作者
                            .outputDir("F:\Study\code\wealth\wealth-admin\src"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    // 设置父包名
                    builder.parent("com.wen.wealth")
                            // 设置父包模块名
                            .moduleName("system")
                            // 设置mapperXml生成路径
                            .pathInfo(Collections.singletonMap(OutputFile.xml, "F:\Study\code\wealth\wealth-admin\src\com\wen\wealth\system\xml"));
                })
                .strategyConfig(builder -> {
                    // 设置需要生成的表名
                    builder.addInclude(tableName)
                            // 设置过滤表前缀
                            .addTablePrefix("sys_")
                            // 开启生成@RestController 控制器
                            .controllerBuilder().enableRestStyle();
                })
                .execute();
    }

}

配置数据库以及代码生成规则就差不多完成全部工程了,经过测试可以通过默认模板生成代码,这边我就先不自己写模板了,上面都有注释应该很好理解,这里只教使用,具体的配置规则可以去看 mybatis-plus官网配置说明

测试代码生成功能

image.png

image.png 调用接口可以看到生成相关代码了

上述就是全部流程,新人可以上手试试,很简单的!加油!