mybatis-plus 自动生成代码

2023-09-16 20:48:03

引入依赖


        <!-- 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://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();

    }




}

更多推荐

网络安全(黑客)自学

前言:作为一个合格的网络安全工程师,应该做到攻守兼备,毕竟知己知彼,才能百战百胜。谈起黑客,可能各位都会想到:盗号,其实不尽然;黑客是一群喜爱研究技术的群体,在黑客圈中,一般分为三大圈:娱乐圈技术圈职业圈。娱乐圈:主要是初中生和高中生较多,玩网恋,人气,空间,建站收徒玩赚钱,技术高的也是有的,只是很少见。技术圈:这个圈

英伟达 nvidia 官方code llama在线使用

新一代编程语言模型CodeLlama面世:重新定义编程的未来随着人工智能和机器学习技术的迅速发展,我们现在迎来了一款革命性的大型编程语言模型——CodeLlama。该模型是基于Llama2研发的,为开放模型中的佼佼者,其性能达到了行业领先水平。模型特点与亮点CodeLlama系列提供多种型号,以满足不同应用的需求。包括

C#流Stream与IO详解(4)——如何更快的读写文件

【前言】在我们追求更快读写速度时,通常都是为了读写二进制文件,而不是文本文件,所以这里只说FileStream、BinaryReader、BinaryWriter的使用。从前文的源码解读中能看到使用BinaryReader和BinaryWriter进行IO读写时本质还是调用了FileStream的接口,所以我们这里只说

从追问AI到人机融合再到人机环境系统智能

人工智能与人类的多元价值对齐是一个复杂而重要的问题。虽然人工智能系统具有强大的计算和学习能力,但它们缺乏人类的情感、道德判断和伦理意识。然而,以下几个方面可以帮助实现人工智能与人类的多元价值对齐:(1)制定明确的伦理框架和规范,对人工智能系统的设计、开发和应用进行指导。这些框架和规范应考虑到人权、公平性、责任、隐私保护

中兴R5300 G4服务器iSAC管理员zteroot密码遗失的重置方法及IPV6地址启用设置

本文讲解中兴R5300G4服务器BMC带外iSAC管理员zteroot密码遗失,无法登录时如何对其进行密码重置,以及iSAC启用IPV6地址的方法。一、重置中兴R5300G4服务器iSAC管理员zteroot密码1、通过SSH登录到iSAC,默认用户名:sysadmin,密码:superuser,如有修改,请输入修改后

金属热处理 术语

声明本文是学习GB-T7232-2023金属热处理术语.而整理的学习笔记,分享出来希望更多人受益,如果存在侵权请及时联系我们1范围本文件界定了金属热处理基础、热处理工艺、组织与性能和热处理装备的主要术语及其定义。本文件适用于金属热处理相关技术标准及技术文件。2规范性引用文件本文件没有规范性引用文件。3基础术语3.1总称

Java之stream流的详细解析一

2.Stream流2.1体验Stream流【理解】案例需求按照下面的要求完成集合的创建和遍历创建一个集合,存储多个字符串元素把集合中所有以"张"开头的元素存储到一个新的集合把"张"开头的集合中的长度为3的元素存储到一个新的集合遍历上一步得到的集合原始方式示例代码publicclassMyStream1{publicst

什么是 Redis?

Redis是一种基于内存的数据库,对数据的读写操作都是在内存中完成的,因此读写速度非常快,常用于缓存,消息队列,分布式锁等场景。Redis提供了多种数据类型来支持不同的业务场景,比如String(字符串)、Hash(哈希)、List(列表)、Set(集合)、Zset(有序集合)、Bitmaps(位图)、HyperLog

400电话的办理和申请流程详解

导语:随着企业的发展和市场竞争的加剧,越来越多的企业开始关注客户服务体验的提升。而办理400电话成为了企业提升客户服务质量的重要手段之一。本文将详细介绍400电话的办理和申请流程,帮助企业了解如何顺利获得400电话。一、了解400电话的概念和优势400电话是一种虚拟电话号码,以400开头,由运营商提供的电话服务。相比于

QT&C++ day12

注册登录界面widget.h#ifndefWIDGET_H#defineWIDGET_H#include<QWidget>#include<QIcon>#include<QPushButton>#include<QLineEdit>#include<QLabel>#include<QDebug>#include<QMe

Ubuntu 22 Docker的使用和安装

确认系统内核版本不低于3.10,并且是64位系统,在终端执行以下命令验证内核及系统信息:$uname-aLinuxVM-4-14-ubuntu5.15.0-76-generic#83-UbuntuSMPThuJun1519:16:32UTC2023x86_64x86_64x86_64GNU/Linux通过上面的输出可知

热文推荐