1. 导入代码生成依赖

主要依赖于mybatis-plus-generator和模板引擎,这里使用的是freemarker,也可以使用其他模板引擎。

     <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></dependency><!-- 添加mysql驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- 添加mybatis-plus组件 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.3.1.tmp</version></dependency><!-- 添加Mybatis-plus自动代码生成器组件,需要排除mybatis-plus组件依赖,否则会覆盖掉mybatis-plus-boot-starter中依赖的版本 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.2.0</version><exclusions><exclusion><groupId>com.baomidou</groupId><artifactId>mybatis-plus-extension</artifactId></exclusion></exclusions></dependency><!-- 引入freemarker模板引擎,做代码模板 --><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId></dependency>
2. 创建代码生成器

以下创建了一个CodeGenerator用于生成controller、service、serviceImpl、entity、mapper、mapper.xml等模板代码,可直接拷贝使用。参考MyBatis-Plus代码生成器。这里我扩展了一个customPackagePath方法,通过内部提供的packageInfo和pathInfo可自定义灵活配置包路径文件路径,详情参见代码注释。

package com.study.mybatisplus.generator;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.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;import java.io.File;
import java.lang.reflect.Field;
import java.util.*;/*** @Auther: LiaoPeng* @Date: 2020/4/12*/
public class CodeGenerator {/*** <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) throws NoSuchFieldException, IllegalAccessException {// 代码生成器AutoGenerator mpg = new AutoGenerator();// 全局配置GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir");gc.setOutputDir(projectPath + "/src/main/java");gc.setFileOverride(true);gc.setOpen(true);gc.setBaseResultMap(true);gc.setBaseColumnList(true);gc.setAuthor("liaopeng");gc.setOpen(false);
//      gc.setSwagger2(true); //实体属性 Swagger2 注解mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc =new DataSourceConfig().setDbQuery(new MySqlQuery() {/*** 重写父类预留查询自定义字段<br>* 这里查询的 SQL 对应父类 tableFieldsSql 的查询字段,默认不能满足你的需求请重写它<br>* 模板中调用:  table.fields 获取所有字段信息,* 然后循环字段获取 field.customMap 从 MAP 中获取注入字段如下  NULL 或者 PRIVILEGES*/@Overridepublic String[] fieldCustom() {return new String[]{"NULL", "PRIVILEGES"};}});dsc.setUrl("jdbc:mysql://localhost:3306/movie?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai");
//      dsc.setSchemaName("public");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("123456");mpg.setDataSource(dsc);// 包配置PackageConfig pc = new PackageConfig();pc.setModuleName(scanner("模块名"));
//        pc.setParent("com.study.mybatisplus");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.setFileCreate(new IFileCreate() {@Overridepublic boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {// 判断自定义文件夹是否需要创建checkDir("调用默认方法创建的目录,自定义目录用");if (fileType == FileType.MAPPER) {// 已经生成 mapper 文件判断存在,不想重新生成返回 falsereturn !new File(filePath).exists();}// 允许生成模板文件return true;}});*/
//        cfg.setFileOutConfigList(focList);
//        mpg.setCfg(cfg);// 配置模板
//        TemplateConfig templateConfig = new TemplateConfig();
//
//        // 配置自定义输出模板
//        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
//        templateConfig.setEntity("templates/entity.java");
//        templateConfig.setService("templates/service.java");
//        templateConfig.setServiceImpl("templates/serviceImpl.java");
//        templateConfig.setController("templates/controller.java");
//        templateConfig.setMapper("templates/mapper.java");
//        templateConfig.setXml("templates/mapper.xml");
//
//        mpg.setTemplate(templateConfig);// 策略配置StrategyConfig strategy = new StrategyConfig();strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setSuperEntityClass("com.mybatisplus.movie.common.BaseEntity");strategy.setEntityLombokModel(true);strategy.setRestControllerStyle(true);// 公共父类
//        strategy.setSuperControllerClass("com.mybatisplus.movie.common.BaseController");// 写于父类中的公共字段strategy.setSuperEntityColumns("id");strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));strategy.setControllerMappingHyphenStyle(true);
//        strategy.setTablePrefix(pc.getModuleName() + "_");strategy.setEntityColumnConstant(true);strategy.setEntityBuilderModel(true);strategy.setEntityTableFieldAnnotationEnable(true);mpg.setStrategy(strategy);mpg.setTemplateEngine(new FreemarkerTemplateEngine());//自定义文件生成路径,包路径//这里调用customPackagePath方法,使用可以自己在内部灵活配置路径//如果不调用该方法、就会使用MyBatis-Plus默认的文件生成路径和包路径生成文件、但可以使用上面的PackageConfig做一些简单的配置customPackagePath(pc,mpg);mpg.execute();}/*** 自定义包路径,文件生成路径,这边配置更灵活* 虽然也可以使用InjectionConfig设置FileOutConfig的方式设置路径* 这里直接使用Map方式注入ConfigBuilder配置对象更加直观* @param pc* @param mpg* @throws NoSuchFieldException* @throws IllegalAccessException*/public static void customPackagePath(PackageConfig pc,AutoGenerator mpg) throws NoSuchFieldException, IllegalAccessException {String projectPath = System.getProperty("user.dir");String mavenPath = "\\src\\main\\java\\";String srcPath = projectPath+mavenPath;String moduleName = pc.getModuleName();/*** packageInfo配置controller、service、serviceImpl、entity、mapper等文件的包路径* 这里包路径可以根据实际情况灵活配置*/Map<String,String> packageInfo = new HashMap<>();packageInfo.put(ConstVal.CONTROLLER, "com.study.mybatisplus.controller."+moduleName);packageInfo.put(ConstVal.SERVICE, "com.study.mybatisplus.services."+moduleName+".service");packageInfo.put(ConstVal.SERVICE_IMPL, "com.study.mybatisplus.services."+moduleName+".service.impl");packageInfo.put(ConstVal.ENTITY, "com.study.mybatisplus.entity."+moduleName);packageInfo.put(ConstVal.MAPPER, "com.study.mybatisplus.mapper."+moduleName);/*** pathInfo配置controller、service、serviceImpl、entity、mapper、mapper.xml等文件的生成路径* srcPath也可以更具实际情况灵活配置* 后面部分的路径是和上面packageInfo包路径对应的源码文件夹路径* 这里你可以选择注释其中某些路径,可忽略生成该类型的文件,例如:注释掉下面pathInfo中Controller的路径,就不会生成Controller文件*/Map pathInfo = new HashMap<>();pathInfo.put(ConstVal.CONTROLLER_PATH, srcPath + packageInfo.get(ConstVal.CONTROLLER).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));pathInfo.put(ConstVal.SERVICE_PATH, srcPath + packageInfo.get(ConstVal.SERVICE).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));pathInfo.put(ConstVal.SERVICE_IMPL_PATH, srcPath + packageInfo.get(ConstVal.SERVICE_IMPL).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));pathInfo.put(ConstVal.ENTITY_PATH, srcPath + packageInfo.get(ConstVal.ENTITY).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));pathInfo.put(ConstVal.MAPPER_PATH, srcPath + packageInfo.get(ConstVal.MAPPER).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));pathInfo.put(ConstVal.XML_PATH, projectPath+"\\src\\main\\resources\\mapper\\"+moduleName);pc.setPathInfo(pathInfo);/*** 创建configBuilder对象,传入必要的参数* 将以上的定义的包路径packageInfo配置到赋值到configBuilder对象的packageInfo属性上* 因为packageInfo是私有成员变量,也没有提交提供公共的方法,所以使用反射注入* 为啥要这么干,看源码去吧*/ConfigBuilder configBuilder = new ConfigBuilder(mpg.getPackageInfo(), mpg.getDataSource(), mpg.getStrategy(), mpg.getTemplate(), mpg.getGlobalConfig());Field packageInfoField = configBuilder.getClass().getDeclaredField("packageInfo");packageInfoField.setAccessible(true);packageInfoField.set(configBuilder,packageInfo);/*** 设置配置对象*/mpg.setConfig(configBuilder);}
}
3. 自定义代码模板

可以在代码生成器的jar包中找到你需要的模板拷贝并进行修改,然后使用以上的TemplateConfig对象配置你修改后的模板的位置。

MyBatis-Plus代码生成器,如何自定义代码生成路径相关推荐

  1. Mybatis Plus————代码生成器

    代码生成器 MyBatis Plus是MyBatis的扩展框架,而代码生成器是MP的核心功能之一,另外还有 "条件构造器"和"通用CRUD"等功能. 步骤演示 ...

  2. MyBatis Plus Generator——MyBatis Plus代码生成器DEMO

    官方文档 https://mp.baomidou.com/guide/generator.html Maven <dependency><groupId>mysql</g ...

  3. Mybatis Plus 代码生成器-让上班划水不再是梦

    文章目录 1. 废话哔哔 2. 开搞 2.1 核心maven依赖 2.2 Spring Boot主要配置 2.3 Mybatis Plus 代码生成器代码 2.4生成的代码结构如下 1. 废话哔哔 不 ...

  4. 取代 Mybatis Generator,这款代码生成神器配置更简单,开发效率更高

    作为一名 Java 后端开发,日常工作中免不了要生成数据库表对应的持久化对象 PO,操作数据库的接口 DAO,以及 CRUD 的 XML,也就是 mapper. Mybatis Generator 是 ...

  5. 如何将自定义代码生成TVM

    如何将自定义代码生成TVM 如何将自定义代码生成TVM 本文参考链接: https://tvm.apache.org/docs/dev/how_to/relay_bring_your_own_code ...

  6. php后台代码自动生成程序,Thinkphp自定义代码生成工具及用法说明(附下载地址)...

    本文实例讲述了Thinkphp自定义代码生成工具及用法说明.分享给大家供大家参考,具体如下: 我最近沮丧的发现在使用Thinkphp很多时候我都在做重复的事情,比如重复写最简单的CRUD方法,编写表单 ...

  7. MyBatis Generator 代码生成器

    MyBatis Generator 代码生成器 MyBatis Generator简介 MyBatis Generator(MBG)是MyBatis 的代码生成器.它将为MyBatis的所有版本生成代 ...

  8. tomcat 设定自定义图片路径

    1.问题 平常图片路径都是在项目目录下存放,都是ip地址+端口号+项目名+图片路径,因为项目需要要把图片从tomcat中分离出来,并且设置可以通过自定义地址访问自定义图片路径. 2.解决 在 tomc ...

  9. win10子系统ubuntu文件夹位置_win10子系统(WSL)自定义安装路径

    1.下载linux安装包: 下载地址:https://docs.microsoft.com/en-us/windows/wsl/install-manual 官方提供的离线安装包有 Ubuntu 18 ...

最新文章

  1. 紫书 习题 10-20 UVa 1648 (推公式)
  2. 编程语言“铁三角”,JavaScript 力压 Java和Python
  3. 【Python位运算】——左移操作(<<)右移操作>>
  4. 除掉字符串里面相同的字符
  5. require.js的基本用法
  6. 人生价值观的培养和建立
  7. Scrapy-redis分布式爬虫
  8. 小学计算机教室管理制度范本,《中小学微机室规章制度》.doc
  9. 面试被问到会不会移动端_问题解答 | 盘点教师资格证面试时一般会问到的问题...
  10. 找换硬币问题 与 0-1背包问题区别
  11. 国笔手机输入法MTK支持的语言
  12. Max Core Frequency 异常显示为-1.80GHz -- Intel-Extreme-Tuning-Utility-Intel-XTU (英特尔 XTU)
  13. php命名空间namespace应用
  14. 数据结构——二叉树相关练习题
  15. wincap函数用法简述
  16. 美国大学计算机专业排名2014,2014年美国大学计算机专业排名
  17. android应用商店app图标大小,各大应用商店APP发布截图尺寸
  18. 浅谈《守望先锋》中的 ECS 构架
  19. oracle环境配置全过程
  20. 删除微软office正版验证补丁

热门文章

  1. 独角兽项目 9 - 一波三折的上线
  2. 11种常用名片设计构图
  3. matlab解析单片机发送数据的一种简单方法
  4. linux安装网卡图解,Linux系统环境下新手如何安装网卡
  5. 不动点(Fixed Point)
  6. 高精度加法------C++
  7. 在Android中访问内置SE和基于SE的卡模拟(一)
  8. 台达,AS228T,plc程序模板和触摸屏程序模板,目前6个总线伺服,采用CANOPEN,适用于运动轴控制,程序可以在自动的时候暂停进行手动控制
  9. c语言十进制转换成k进制,C语言10进制转换为k进制的问题
  10. # 研究杂感 × Gephi探秘飞升(第三辑)