MyBatisPlus学习日记01-代码生成器

代码生成器

package cn.util;

import java.util.Scanner;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

public class CodeGenerator {
    // 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中

    /**
     * <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 mpg = new AutoGenerator();
        // 选择 freemarker 引擎,默认 Veloctiy
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");    //生成文件的输出目录
        gc.setAuthor("madz");                    //作者
        gc.setFileOverride(true);                //是否覆蓋已有文件 默认值:false
        gc.setOpen(false);                        //是否打开输出目录 默认值:true

//	        gc.setSwagger2(true);					//开启 swagger2 模式 默认false
        gc.setBaseColumnList(true);                //开启 baseColumnList 默认false
        gc.setBaseResultMap(true);                //开启 BaseResultMap 默认false
        gc.setEntityName("%sEntity");            //实体命名方式  默认值:null 例如:%sEntity 生成 UserEntity
        gc.setMapperName("%sMapper");            //mapper 命名方式 默认值:null 例如:%sDao 生成 UserDao
        gc.setXmlName("%sMapper");                //Mapper xml 命名方式   默认值:null 例如:%sDao 生成 UserDao.xml
        gc.setServiceName("%sService");            //service 命名方式   默认值:null 例如:%sBusiness 生成 UserBusiness
        gc.setServiceImplName("%sServiceImpl");    //service impl 命名方式  默认值:null 例如:%sBusinessImpl 生成 UserBusinessImpl
        gc.setControllerName("%sController");    //controller 命名方式    默认值:null 例如:%sAction 生成 UserAction
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);        //数据库类型	该类内置了常用的数据库类型【必须】
        dsc.setUrl("jdbc:mysql://localhost:3306/leantest?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
//	        pc.setModuleName(scanner("模块名"));
        pc.setParent("cn.ds.car");
        mpg.setPackageInfo(pc);

        // 自定义配置
//	        InjectionConfig cfg = new InjectionConfig() {
//	            @Override
//	            public void initMap() {		//注入自定义 Map 对象
//	                // to do nothing
//	            }
//	        };
//	        List<FileOutConfig> focList = new ArrayList<>();
//	        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
//	            @Override
//	            public String outputFile(TableInfo tableInfo) {
//	                // 自定义输入文件名称
//	                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
//	                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
//	            }
//	        });
//	        cfg.setFileOutConfigList(focList);
//	        mpg.setCfg(cfg);
//	        mpg.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置	数据库表配置,通过该配置,可指定需要生成哪些表或者排除哪些表
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);    //表名生成策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
//	        strategy.setCapitalMode(true);			// 全局大写命名 ORACLE 注意
//	        strategy.setTablePrefix("prefix");		//表前缀
//	        strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");	//自定义继承的Entity类全称,带包名
//	        strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); 	//自定义实体,公共字段
        strategy.setEntityLombokModel(true);    //【实体】是否为lombok模型(默认 false
        strategy.setRestControllerStyle(true);    //生成 @RestController 控制器
//	        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");	//自定义继承的Controller类全称,带包名
        strategy.setInclude(scanner("表名"));        //需要包含的表名,允许正则表达式(与exclude二选一配置)
//	        strategy.setInclude(new String[] { "user" }); // 需要生成的表可以多张表
//	        strategy.setExclude(new String[]{"test"}); // 排除生成的表
        strategy.setControllerMappingHyphenStyle(true);    //驼峰转连字符
        strategy.setTablePrefix(pc.getModuleName() + "_");    //是否生成实体时,生成字段注解
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

可以使用自定义配置
以上配置是单表操作,设置 以下属性可以多表操作,具体需求设置主要在
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));

p.s.问题

需要的依赖问题,习惯项目依赖父项目spring-boot-starter-parent,

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Mybatis-Plus提供了一个非常方便的代码生成器,可以快速生成基础的CRUD操作代码。以下是生成器的最全代码: 1. 配置代码生成器 ```java public class CodeGenerator { public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("author"); gc.setOpen(false); gc.setSwagger2(true); gc.setBaseResultMap(true); gc.setBaseColumnList(true); gc.setFileOverride(true); gc.setIdType(IdType.AUTO); gc.setServiceName("%sService"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.example.demo"); pc.setModuleName("module"); pc.setController("controller"); pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setServiceImpl("service.impl"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm"; // 自定义输出配置 List<FileOutConfig> focList = new ArrayList<>(); // 自定义配置会被优先输出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名,如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); // 配置自定义输出模板 // templateConfig.setEntity(); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 公共父类 // strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); // 写于父类中的公共字段 // strategy.setSuperEntityColumns("id"); strategy.setInclude("user"); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } } ``` 2. 运行代码生成器 在main方法中运行代码生成器即可生成代码。 ```java public static void main(String[] args) { // 代码生成器配置... // ... mpg.execute(); } ``` 以上就是Mybatis-Plus最全全的代码生成器的代码。你可以根据需要进行修改,比如修改输出路径、修改数据源配置等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值