SpringBoot 结合 Mybatis Plus 自动生成代码

本文介绍如何使用SpringBoot结合MybatisPlus自动生成代码,包括导入依赖、配置全局参数、数据源、包结构等步骤,并提供了一个完整的代码生成器实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot 结合 Mybatis Plus 自动生成代码

具体实现如下

导入依赖

在使用SpringBoot结合Mybatis Plus自动生成代码之前,需要导入Mybatis Plus自动生成代码对应的依赖,具体如下:

	<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>VersionId</version>
    </dependency>

在后续自动生成器实现中,需要使用到模板引擎,所以我们也需要导入模板引擎依赖,在本文中使用的是Freemarker模板引擎,所以依赖为:

	<dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>${freemarker.version}</version>
    </dependency>

补充:Mybtis-Plus支持 Velocity(默认)、Freemarker、Beetl,三种模板引擎,用户也可以选择自己定义的模板引擎。

代码实现

在实现中,首先应该定义一个代码生成器:AutoGenerator autoGenerator = new AutoGenerator();,然后需要进行一些全局配置、数据源配置、包配置、自定义配置(可选)、模板配置、策略配置、模板引擎配置,最后开始执行代码生成器autoGenerator
具体代码如下:

package com.example.codeAutoGenerate.utils;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @Date: 2021/2/1
 * @Msg:
 */
public class MyCodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator autoGenerator = new AutoGenerator();

        String projectPath = System.getProperty("user.dir"); // D:\github\projectName

        // 全局配置
        autoGenerator.setGlobalConfig(initGlobal(projectPath));

        // 数据源配置
        autoGenerator.setDataSource(initDataSource());

        // 包配置
        PackageConfig pc = new PackageConfig();
        autoGenerator.setPackageInfo(initPackage(pc));

        //自定义配置
        autoGenerator.setCfg(initInjection(projectPath));

        // 配置模板
        autoGenerator.setTemplate(initTemplate());

        // 策略配置
        autoGenerator.setStrategy(initStrategy(pc));

        //模板引擎设置
        autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());

        //执行
        autoGenerator.execute();
    }

    private static StrategyConfig initStrategy(PackageConfig pc){
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(scanner("表名"));
        strategy.setSuperEntityColumns("id");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        return strategy;
    }

    private static TemplateConfig initTemplate(){
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        return templateConfig;
    }

    private static InjectionConfig initInjection(String projectPath){
        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名
                return projectPath + "/src/main/resources/mapper/" + "/" + tableInfo.getMapperName() + StringPool.DOT_XML;
            }
        });
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        cfg.setFileOutConfigList(focList);
        return cfg;
    }

    private static PackageConfig initPackage(PackageConfig pc){
        pc.setParent("com.example");
        pc.setModuleName(scanner("模块名"));
        return pc;
    }

    private static GlobalConfig initGlobal(String projectPath){
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("lana");
        gc.setOpen(false);
        gc.setEntityName("%sEntity");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        return gc;
    }

    private static DataSourceConfig initDataSource(){
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://hostIP:3306/schemaName?characterEncoding=UTF-8&serverTimezone=UTC");
        dsc.setSchemaName("schemaName");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("userName");
        dsc.setPassword("password");
        return dsc;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值