AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以根据模板快速生成代码,方便前后端的工作。
- 添加代码生成器依赖
com.baomidou mybatis-plus-generator3.5.0
- 添加模板引擎依赖
org.apache.velocity velocity-engine-core2.3
MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,可以采用自定义模板引擎。
注意!如果您选择了非默认引擎,需要在 AutoGenerator 中 设置模板引擎。
AutoGenerator generator = new AutoGenerator(); // set freemarker engine generator.setTemplateEngine(new FreemarkerTemplateEngine()); // set beetl engine generator.setTemplateEngine(new BeetlTemplateEngine()); // set custom engine (reference class is your custom engine class) generator.setTemplateEngine(new CustomTemplateEngine()); // other config ...
- 编写配置
配置 GlobalConfig
GlobalConfig globalConfig = new GlobalConfig(); globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java"); globalConfig.setAuthor("jobob"); globalConfig.setOpen(false);
配置 DataSourceConfig
DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8"); dataSourceConfig.setDriverName("com.mysql.jdbc.Driver"); dataSourceConfig.setUsername("root"); dataSourceConfig.setPassword("password");
- 自定义代码模板
//指定自定义模板路径, 位置:/resources/templates/entity2.java.ftl(或者是.vm) //注意不要带上.ftl(或者是.vm), 会根据使用的模板引擎自动识别 TemplateConfig templateConfig = new TemplateConfig() .setEntity("templates/entity2.java"); AutoGenerator mpg = new AutoGenerator(); //配置自定义模板 mpg.setTemplate(templateConfig);
- 自定义属性注入
InjectionConfig injectionConfig = new InjectionConfig() { //自定义属性注入:abc //在.ftl(或者是.vm)模板中,通过${cfg.abc}获取属性 @Override public void initMap() { Mapmap = new HashMap<>(); map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); this.setMap(map); } }; AutoGenerator mpg = new AutoGenerator(); //配置自定义属性注入 mpg.setCfg(injectionConfig);
entity2.java.ftl 自定义属性注入abc=${cfg.abc} entity2.java.vm 自定义属性注入abc=$!{cfg.abc}
- Velocity模板引擎
Velocity将Java代码从Web 页面中分离出来,使用Web站点从长远看更容易维护,并且提供了一种可行的JavaServer Pages替代解决方案。
Velocity是一种基于Java的模板引擎,但允许任何人使用简单而强大的模板语言来引用定义在Java代码中的对象。
基本语法 关键字
Velocity关键字都是使用#开头的,如#set、#if、#else、#end、#foreach等
$ 变量
Velocity变量都是使用 开 头 的 , 如 : 开头的,如: 开头的,如:name、$msg
{}变量
Velocity对于需要明确表示的Velocity变量,可以使用{}将变量包含起来。如在页面中,需要有 $ someoneName这种内容,此时为了让Velocity能够区分,可以使用${someone}Name。
!变量
如果某个Velocity变量不存在,那么页面中就会显示$ xxx的形式,为了避免这种形式,可以在变量名称前加上!如页面中含有$ msg,如果msg有值,将显示msg的值;如果不存在就会显示$ msg。这是我们不希望看到的,为了把不存在的变量显示为空白,可以使用$!msg。
变量
变量定义
#set($root = "www") #set($name = "index") #set($template = "$root/$name") $template
执行输出结果
www/index
变量赋值
赋值的左边必须是一个变量,或者是属性的引用。右边可以是:变量引用、字面字符串、属性引用、方法引用、字面数字、数组
#set($name = $bill) ##变量引用 #set($name.pre = "monica") ##字符串 #set($name.last = $address.num) ##属性引用 #set($name.mid = $hotel.find($web)) ##方法引用 #set($name.num = 123) ##数字 #set($name.say = ["yes",$my,"yes"]) ##数组
velocity会将属性解释为属性的get方法,如:
$foo.Bar 等同于 $foo.getBar() $foo.User("join") 等同于 $foo.getUser("join") $foo.Request.ServerName 等同于 $foo.getRequest().getServerName()
转义字符’’
#set($mail = "foo") $mail $mail $mail $mail
执行结果
foo $mail foo $mail
循环
#foreach( $num in [2..-2]) this is $num. #end
this is 2. this is 1. this is 0. this is -1. this is -2
条件
#if(condition) ...... #elseif(condition) ...... #else ...... #end
关系和逻辑 *** 作符
&& 并且 || 或者 ! 取反
注释
##单行注释 #* 多行的注释 *#
- demo
spring-boot-plus代码生成器入口类
package test; public class SpringBootPlusGenerator { public static void main(String[] args) { CodeGenerator codeGenerator = new CodeGenerator(); // 公共配置 // 数据库配置 codeGenerator .setUserName("root") .setPassword("root") .setDriverName("com.mysql.cj.jdbc.Driver") .setDriverUrl("jdbc:mysql://localhost:3306/nhyj?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC"); // 包信息 codeGenerator .setProjectPackagePath("com/sinosoft/springbootplus") .setParentPackage("com.sinosoft.springbootplus"); // 组件作者等配置 codeGenerator .setProjectName("jwpx") .setModuleName("project") .setAuthor("fan") .setPkIdColumnName("id"); // 生成策略 codeGenerator .setGeneratorStrategy(CodeGenerator.GeneratorStrategy.ALL) .setPageListOrder(true) .setParamValidation(true); // 生成实体映射相关代码,可用于数据库字段更新 // 当数据库字段更新时,可自定义自动生成哪些那文件 codeGenerator .setGeneratorEntity(true) .setGeneratorQueryParam(true) .setGeneratorQueryVo(true); // 生成业务相关代码 codeGenerator .setGeneratorController(true) .setGeneratorService(true) .setGeneratorServiceImpl(true) .setGeneratorMapper(true) .setGeneratorMapperXml(true) .setGeneratorEditHtml(true) .setGeneratorListHtml(true) .setGeneratiorEvent(true) .setMockJs(true) .setInterfaceJs(true); // 是否生成Shiro RequiresPermissions注解 codeGenerator.setRequiresPermissions(true); // 是否覆盖已有文件 codeGenerator.setFileOverride(true); // 初始化公共变量 codeGenerator.init(); // 需要生成的表数组 // xxx,yyy,zzz为需要生成代码的表名称 String[] tables = { "sys_dict" }; //如果生成html则设置html目录,aa/bb/cc =》["aa","bb","cc"] codeGenerator.setPath(new String[]{"user","test"}); // 循环生成 for (String table : tables) { // 设置需要生成的表名称 codeGenerator.setTableName(table); // 生成代码 codeGenerator.generator(); } } }
spring-boot-plus代码生成器
package test; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; 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.TableFill; 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 lombok.Data; import lombok.experimental.Accessors; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Data @Accessors(chain = true) public class CodeGenerator { private String userName; private String password; private String driverName; private String driverUrl; private String projectPackagePath; private String parentPackage; private String packageController = "controller"; // ############################ 自定义配置部分 start ############################ private String moduleName; private String projectName =""; private String author; private String tableName; private String pkIdColumnName = "id"; private GeneratorStrategy generatorStrategy = GeneratorStrategy.ALL; public enum GeneratorStrategy { SIMPLE, NORMAL, ALL } private boolean pageListOrder = false; private boolean paramValidation = true; private boolean generatorEntity; private boolean generatorController; private boolean generatorService; private boolean generatorServiceImpl; private boolean generatorMapper; private boolean generatorMapperXml; private boolean generatiorEvent; private boolean generatorListHtml; private boolean generatorEditHtml; private boolean generatorActivitiTable; private boolean generatorQueryParam; private boolean generatorQueryVo; private boolean requiresPermissions; private boolean mockJs; private boolean interfaceJs; // ############################ 自定义配置部分 end ############################ private String commonParentPackage; private String mybatisParentPackage; private String superEntity; private String superController; private String superService; private String superServiceImpl; private String superQueryParam; private String[] superEntityCommonColumns; // 公共类包路径 private String commonIdParam; private String commonApiResult; private String commonOrderEnum; private String commonOrderQueryParam; private String commonPaging; private boolean fileOverride; // 自定义需要填充的字段 private List tableFillList = new ArrayList<>(); private String[] path; public void init() { this.commonParentPackage = this.parentPackage + ".common"; this.mybatisParentPackage =this.parentPackage + ".mybatis"; // 父类包路径 this.superEntity = this.commonParentPackage + ".entity.baseEntity"; this.superController = this.commonParentPackage + ".controller.baseController"; this.superService = this.mybatisParentPackage + ".service.baseService"; this.superServiceImpl = this.mybatisParentPackage + ".service.impl.baseServiceImpl"; this.superQueryParam = this.mybatisParentPackage + ".param.QueryParam"; this.superEntityCommonColumns = new String[]{}; // 公共类包路径 this.commonIdParam = this.commonParentPackage + ".param.IdParam"; this.commonApiResult = this.commonParentPackage + ".api.ApiResult"; this.commonOrderEnum = this.commonParentPackage + ".enums.OrderEnum"; this.commonOrderQueryParam = this.mybatisParentPackage + ".param.OrderQueryParam"; this.commonPaging = this.mybatisParentPackage+".vo.Paging"; tableFillList.add(new TableFill("update_time", FieldFill.UPDATE)); tableFillList.add(new TableFill("update_by", FieldFill.UPDATE)); tableFillList.add(new TableFill("create_time", FieldFill.INSERT)); tableFillList.add(new TableFill("create_by", FieldFill.INSERT)); } public void generator() { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/"+projectName+"/src/main/java"); gc.setAuthor(author); gc.setOpen(false); // 是否打开输出目录 gc.setSwagger2(true); // 启用swagger注解 gc.setIdType(IdType.ID_WORKER); // 主键类型:ID_WORKER gc.setServiceName("%sService"); // 自定义文件命名,注意 %s 会自动填充表实体属性! gc.setFileOverride(fileOverride); // 是否覆盖已有文件 gc.setDateType(DateType.ONLY_DATE); // 设置日期类型为Date mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl(driverUrl); // dsc.setSchemaName("public"); dsc.setDriverName(driverName); dsc.setUsername(userName); dsc.setPassword(password); // 设置自定义查询 dsc.setDbQuery(new com.sinosoft.springbootplus.mybatis.generator.config.SpringBootPlusMySqlQuery()); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName(moduleName); pc.setParent(parentPackage); pc.setController(packageController); pc.setService("application.service"); pc.setServiceImpl("application.service.impl"); pc.setMapper("domain.mapper"); pc.setEntity("domain.entity"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { String camelTableName = underlineToCamel(tableName); String pascalTableName = underlineToPascal(tableName); String colonTableName = underlineTocolon(tableName); Mapmap = new HashMap<>(); map.put("customField", "Hello " + this.getConfig().getGlobalConfig().getAuthor()); // 查询参数包路径 String queryParamPackage = parentPackage + StringPool.DOT + pc.getModuleName() + ".param"; map.put("queryParamPackage", queryParamPackage); // 查询参数类路径 map.put("queryParamPath", queryParamPackage + StringPool.DOT + pascalTableName + "QueryParam"); // 查询参数共公包路径 map.put("queryParamCommonPath", superQueryParam); // 查询参数共公包路径 map.put("idParamPath", commonIdParam); // 响应结果包路径 String queryVoPackage = parentPackage + StringPool.DOT + pc.getModuleName() + ".vo"; map.put("queryVoPackage", queryVoPackage); // 响应结果类路径 map.put("queryVoPath", queryVoPackage + StringPool.DOT + pascalTableName + "QueryVo"); // 实体对象名称 map.put("entityObjectName", camelTableName); // service对象名称 map.put("serviceObjectName", camelTableName + "Service"); // mapper对象名称 map.put("mapperObjectName", camelTableName + "Mapper"); // 主键ID列名 map.put("pkIdColumnName", pkIdColumnName); // 主键ID驼峰名称 map.put("pkIdCamelName", underlineToCamel(pkIdColumnName)); // 导入分页类 map.put("paging", commonPaging); // 导入排序枚举 map.put("orderEnum", commonOrderEnum); // ApiResult map.put("apiResult", commonApiResult); // 分页列表查询是否排序 map.put("pageListOrder", pageListOrder); // 导入排序查询参数类 map.put("orderQueryParamPath", commonOrderQueryParam); // 代码生成策略 map.put("generatorStrategy", generatorStrategy); // 代码Validation校验 map.put("paramValidation", paramValidation); // 冒号连接的表名称 map.put("colonTableName", colonTableName); // 是否生成Shiro RequiresPermissions注解 map.put("requiresPermissions", requiresPermissions); //================页面生成部分(开始)======== if(generatorListHtml || generatorEditHtml){ map.put("baseLayFilter",StringUtils.join(path,"-")+"-"+camelTableName+"List"); map.put("baseEditPath",StringUtils.join(path,"/")+"/"+camelTableName+"Edit"); } //首字母大写的表名 map.put("TableName", StrUtil.upperFirst(camelTableName)); //首字母小写的表名 map.put("tableName",camelTableName); map.put("publishPackage","com.sinosoft.springbootplus."+moduleName+".application.event.publish"); map.put("pubisherClass",pascalTableName+"Pubisher"); map.put("subscriptionPackage","com.sinosoft.springbootplus."+moduleName+".application.event.subscription"); map.put("subscriptionClass",pascalTableName+"Subscription"); map.put("domainPackage","com.sinosoft.springbootplus."+moduleName+".domain.service"); map.put("domainClass",pascalTableName+"Domain"); map.put("domainClassName",camelTableName+"Domain"); //================页面生成部分(结束)======== this.setMap(map); } }; List focList = new ArrayList<>(); // 生成mapper xml if (generatorMapperXml) { focList.add(new FileOutConfig("/templates/mapper.xml.vm") { @Override public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称 return projectPath + "/"+projectName+"/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); } // 自定义queryParam模板 if (generatorQueryParam) { focList.add(new FileOutConfig("/templates/queryParam.java.vm") { @Override public String outputFile(TableInfo tableInfo) { return projectPath +"/"+projectName+ "/src/main/java/" + projectPackagePath + "/" + pc.getModuleName() + "/param/" + tableInfo.getEntityName() + "QueryParam" + StringPool.DOT_JAVA; } }); } // 自定义queryVo模板 if (generatorQueryVo) { focList.add(new FileOutConfig("/templates/queryVo.java.vm") { @Override public String outputFile(TableInfo tableInfo) { return projectPath + "/"+projectName+"/src/main/java/" + projectPackagePath + "/" + pc.getModuleName() + "/vo/" + tableInfo.getEntityName() + "QueryVo" + StringPool.DOT_JAVA; } }); } if(generatiorEvent){ focList.add(new FileOutConfig("/templates/pubisher.java.vm") { @Override public String outputFile(TableInfo tableInfo) { return projectPath + "/"+projectName+"/src/main/java/" + projectPackagePath + "/" + pc.getModuleName() + "/application/event/publish/" + tableInfo.getEntityName() + "Pubisher" + StringPool.DOT_JAVA; } }); focList.add(new FileOutConfig("/templates/subscription.java.vm") { @Override public String outputFile(TableInfo tableInfo) { return projectPath + "/"+projectName+"/src/main/java/" + projectPackagePath + "/" + pc.getModuleName() + "/application/event/subscription/"+ tableInfo.getEntityName() + "Subscription" + StringPool.DOT_JAVA; } }); focList.add(new FileOutConfig("/templates/domain.java.vm") { @Override public String outputFile(TableInfo tableInfo) { return projectPath + "/"+projectName+"/src/main/java/" + projectPackagePath + "/" + pc.getModuleName() + "/domain/service/" + tableInfo.getEntityName() + "Domain" + StringPool.DOT_JAVA; } }); } // 自定义generatorListHtml模板 if (generatorListHtml) { focList.add(new FileOutConfig("/templates/list.html.vm") { @Override public String outputFile(TableInfo tableInfo) { String camelTableName = underlineToCamel(tableInfo.getName()); return projectPath + "/"+projectName+"/src/main/webapp/src/views/" + StringUtils.join(path,"/") + "/" +camelTableName + "List.html"; } }); } // 自定义generatorListHtml模板 if (generatorEditHtml) { focList.add(new FileOutConfig("/templates/edit.html.vm") { @Override public String outputFile(TableInfo tableInfo) { String camelTableName = underlineToCamel(tableInfo.getName()); return projectPath + "/"+projectName+"/src/main/webapp/src/views/" + StringUtils.join(path,"/") + "/" +camelTableName + "Edit.html"; } }); } //生成mock.js if(mockJs){ focList.add(new FileOutConfig("/templates/mock.js.vm") { @Override public String outputFile(TableInfo tableInfo) { String camelTableName = underlineToCamel(tableInfo.getName()); return projectPath + "/"+projectName+"/src/main/webapp/src/views/" + StringUtils.join(path,"/") + "/" +camelTableName + "Mock.js"; } }); } //生成接口文件 if(interfaceJs){ focList.add(new FileOutConfig("/templates/interface.js.vm") { @Override public String outputFile(TableInfo tableInfo) { String camelTableName = underlineToCamel(tableInfo.getName()); return projectPath + "/"+projectName+"/src/main/webapp/src/views/" + StringUtils.join(path,"/") + "/" +camelTableName + "Interface.js"; } }); } if(generatorActivitiTable){ focList.add(new FileOutConfig("/templates/activitiList.html.vm") { @Override public String outputFile(TableInfo tableInfo) { String camelTableName = underlineToCamel(tableInfo.getName()); return projectPath + "/"+projectName+"/src/main/webapp/src/views/" + StringUtils.join(path,"/") + "/" +camelTableName + "List.html"; } }); focList.add(new FileOutConfig("/templates/activitiList.js.vm") { @Override public String outputFile(TableInfo tableInfo) { String camelTableName = underlineToCamel(tableInfo.getName()); return projectPath + "/"+projectName+"/src/main/webapp/src/views/" + StringUtils.join(path,"/") + "/" +camelTableName + ".js"; } }); focList.add(new FileOutConfig("/templates/edit.html.vm") { @Override public String outputFile(TableInfo tableInfo) { String camelTableName = underlineToCamel(tableInfo.getName()); return projectPath + "/"+projectName+"/src/main/webapp/src/views/" + StringUtils.join(path,"/") + "/" +camelTableName + "Edit.html"; } }); } cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 模版生成配置,设置为空,表示不生成 TemplateConfig templateConfig = new TemplateConfig(); // xml使用自定义输出 templateConfig.setXml(null); // 是否生成entity if (!generatorEntity) { templateConfig.setEntity(null); } // 是否生成controller if (!generatorController) { templateConfig.setController(null); } // 是否生成service if (!generatorService) { templateConfig.setService(null); } // 是否生成serviceImpl if (!generatorServiceImpl) { templateConfig.setServiceImpl(null); } // 是否生成mapper if (!generatorMapper) { templateConfig.setMapper(null); } mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setSuperEntityClass(superEntity); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); strategy.setSuperControllerClass(superController); strategy.setSuperServiceClass(superService); strategy.setSuperServiceImplClass(superServiceImpl); strategy.setInclude(tableName); strategy.setSuperEntityColumns(superEntityCommonColumns); strategy.setControllerMappingHyphenStyle(true); //逻辑删除字段名称 strategy.setLogicDeleteFieldName("deleted"); //乐观锁 strategy.setVersionFieldName("version"); strategy.setTableFillList(tableFillList); //strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.execute(); } public static String underlineToCamel(String underline) { if (StringUtils.isNotBlank(underline)) { return NamingStrategy.underlineToCamel(underline); } return null; } public static String underlineToPascal(String underline) { if (StringUtils.isNotBlank(underline)) { return NamingStrategy.capitalFirst(NamingStrategy.underlineToCamel(underline)); } return null; } public static String underlineTocolon(String underline) { if (StringUtils.isNotBlank(underline)) { String string = underline.toLowerCase(); return string.replaceAll("_", ":"); } return null; } public static void main(String[] args) { System.out.println(underlineTocolon("sys_user")); } }
自定义模板
#foreach($field in ${table.fields}) #end 取消 确定 欢迎分享,转载请注明来源:内存溢出
评论列表(0条)