mybatis-plus 自动生成代码

引入依赖。。。。。


        <!-- mybatis plus 代码生成器引擎依赖-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>
      <!-- mybatis plus 代码生成器依赖 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>

编写java脚本

package com.fy.financialstatement.util;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class MpCode {

    private static String module;
    private static String dbname;
    private static String PACKAGE = "org.example.test";
    private static String AUTHOR = "jz";

    private static String TRICAR_AUTHOR = "jz";
    private static String DATA_USER_NAME = "root";
    private static String TRICAR_DATA_USER_NAME = "jz";
    private static String DATA_PASSWORD = "1a2b3d4e##";
    private static String TRICAR_DATA_PASSWORD = "xhT&YGm4Tp";
    private static String DATA_DRIVER_NAME = "com.mysql.cj.jdbc.Driver";

    private static String DATA_URL = "jdbc:mysql://47.105.213.4:3306/fy_financial_statement?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai";
    private static String TRICAR_DATA_URL = "jdbc:mysql://139.129.89.193:3306/tripcar20230505?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai";

    private static String PATH_MAPPER  = "/src/main/java/org/example/test/";
    private static String PATH_MAPPER_XML = "/src/main/resources/mapper/";
    private static String PATH_CONTROLLER = "/src/main/java/org/example/test/";
    private static String PATH_SERVICE = "/src/main/java/org/example/test/";
    private static String PATH_SERVICE_IMP = "/src/main/java/org/example/test/";
    private static String PATH_ENTITY = "/src/main/java/org/example/test/";


    public static void main(String[] args) {
    https://www.cnblogs.com/Maoscn/p/17777205.html
//https://blog.csdn.net/weixin_45941687/article/details/125971980
       // https://blog.csdn.net/yuandfeng/article/details/129660762
        // https://blog.csdn.net/yelangkingwuzuhu/article/details/128077533
        // https://zhuanlan.zhihu.com/p/365882059
        //https://blog.csdn.net/weixin_52067659/article/details/128356337
        // Properties p = System.getProperties();
        // p.list(System.out);


        module = "/" + scanner("要输入到哪个项目?");
        dbname = scanner("哪个数据库?");
        String[] tables = scanner("请输入要生成的表名多个用 , 分割").split(",");
        for (String table : tables) {
            shell(table);
        }


    }


    public static String scanner(String someThing) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入" + someThing + ":");
        if (scanner.hasNext()) {
            String sc = scanner.next();
            if (!"".equals(sc) && null != sc) {
                return sc;
            }
        }
        throw new MybatisPlusException("请输入正确的" + someThing + "!");
    }


    private static void shell(String table) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDriverName(DATA_DRIVER_NAME);
        if ("tripcar".equals(dbname)) {
            dsc.setUsername(TRICAR_DATA_USER_NAME);
            dsc.setPassword(TRICAR_DATA_PASSWORD);
            dsc.setUrl(TRICAR_DATA_URL);
        }else{
            dsc.setUsername(DATA_USER_NAME);
            dsc.setPassword(DATA_PASSWORD);
            dsc.setUrl(DATA_URL);
        }

        mpg.setDataSource(dsc);

        // 全局配置
        final String projectPath = System.getProperty("user.dir"); // 默认定位到的当前用户目录("user.dir")(即工程根目录) https://blog.csdn.net/qq_29964641/article/details/86686585

        GlobalConfig gc = new GlobalConfig();
        gc.setFileOverride(true);
        gc.setAuthor(AUTHOR);//作者名称
        gc.setDateType(DateType.ONLY_DATE);
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setServiceName("%sService"); //自定义文件命名,注意 %s 会自动填充表实体属性! %s作为占位符

        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");

        gc.setFileOverride(true); //重新生成时文件是否覆盖
        gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
//        gc.setIdType(IdType.ID_WORKER_STR); //主键策略
//        gc.setOutputDir(projectPath + "/src/main/java");
//        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);


        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(PACKAGE);
        pc.setMapper("mapper");//dao
        pc.setService("service");//servcie
        pc.setController("controller");//controller
        pc.setEntity("entity");
//        pc.setModuleName("model名"); 自定义包名

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
//                //表信息
                String name = this.getConfig().getStrategyConfig().getColumnNaming().name();
            }
        };

        // 模板引擎是 freemarker
        // 自定义controller的代码模板
        // 如果模板引擎是 velocity
        String templatePath = "/templates/mapper.xml.vm";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出,配置mapper.xml
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //根据自己的位置修改
                return projectPath  + module + PATH_MAPPER_XML +dbname+"/"+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        //控制层
        templatePath = "/templates/controller.java.vm";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath  + module + PATH_CONTROLLER + "controller/"+dbname;
                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getControllerName());
                return entityFile;
            }
        });

        //业务层
        templatePath = "/templates/service.java.vm";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath  + module + PATH_SERVICE + "service/"+dbname;
                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getServiceName());
                return entityFile;
            }
        });

        templatePath = "/templates/serviceImpl.java.vm";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath  + module + PATH_SERVICE_IMP + "service/impl/"+dbname;
                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getServiceImplName());
                return entityFile;
            }
        });

        //数据层
        templatePath = "/templates/mapper.java.vm";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath + module +PATH_MAPPER + "mapper/"+dbname;
                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getMapperName());
                return entityFile;
            }
        });

        //数据层
        templatePath = "/templates/entity.java.vm";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath + module+PATH_ENTITY + "entity/"+dbname;
                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getEntityName());
                return entityFile;
            }
        });

        mpg.setPackageInfo(pc);
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);


        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        templateConfig.setService("/template/service.java");
        templateConfig.setServiceImpl("/template/serviceImpl.java");
//        templateConfig.setEntity("/template/entity.java.ftl");
//        templateConfig.setMapper("/template/mapper.java.ftl");
//        templateConfig.setController("/template/controller.java.ftl");
        //        //此处设置为null,就不会再java下创建xml的文件夹了
        templateConfig.setXml("/template/mapper.xml");
        mpg.setTemplate(templateConfig);


        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setChainModel(true);
        strategy.setNaming(NamingStrategy.underline_to_camel); // 数据库表映射到实体的命名策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel); //数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true);
        strategy.setEntityTableFieldAnnotationEnable(true);
        strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作

        strategy.setRestControllerStyle(true);
        strategy.setInclude(table); //table 表名对那一张表生成代码
        strategy.setControllerMappingHyphenStyle(true);



//        strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
//        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); // 公共父类
//        strategy.setSuperEntityColumns("id"); //         写于父类中的公共字段
//        strategy.setTablePrefix("t_");  //生成实体时去掉表前缀



        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new VelocityTemplateEngine());//默认模板引擎
        mpg.execute();

    }




}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值