模板引擎是 velocity(默認引擎)
自己可根據需要稍作修改,如果要大改則需要去看模板引擎的語法了。
1、entity.java.vm
package ${package.Entity}; #foreach($pkg in ${table.importPackages}) import ${pkg}; #end #if(${swagger2}) import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; #end #if(${entityLombokModel}) import lombok.Data; import lombok.EqualsAndHashCode; #if(${chainModel}) import lombok.experimental.Accessors; #end #end /** * <p> * $!{table.comment} * </p> * * @author ${author} * @since ${date} */ #if(${entityLombokModel}) @Data #if(${superEntityClass}) @EqualsAndHashCode(callSuper = true) #else @EqualsAndHashCode(callSuper = false) #end #if(${chainModel}) @Accessors(chain = true) #end #end #if(${table.convert}) @TableName("${table.name}") #end #if(${swagger2}) @ApiModel(value="${entity}對象", description="$!{table.comment}") #end #if(${superEntityClass}) public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end { #elseif(${activeRecord}) public class ${entity} extends Model<${entity}> { #else public class ${entity} implements Serializable { #end #if(${entitySerialVersionUID}) private static final long serialVersionUID=1L; #end ## ---------- BEGIN 字段循環遍歷 ---------- #foreach($field in ${table.fields}) #if(${field.keyFlag}) #set($keyPropertyName=${field.propertyName}) #end #if("$!field.comment" != "") #if(${swagger2}) @ApiModelProperty(value = "${field.comment}") #else /** * ${field.comment} */ #end #end #if(${field.keyFlag}) ## 主鍵 #if(${field.keyIdentityFlag}) @TableId(value = "${field.annotationColumnName}", type = IdType.AUTO) #elseif(!$null.isNull(${idType}) && "$!idType" != "") @TableId(value = "${field.annotationColumnName}", type = IdType.${idType}) #elseif(${field.convert}) @TableId("${field.annotationColumnName}") #end ## 普通字段 #elseif(${field.fill}) ## ----- 存在字段填充設置 ----- #if(${field.convert}) @TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill}) #else @TableField(fill = FieldFill.${field.fill}) #end #elseif(${field.convert}) @TableField("${field.annotationColumnName}") #end ## 樂觀鎖注解 #if(${versionFieldName}==${field.name}) @Version #end ## 邏輯刪除注解 #if(${logicDeleteFieldName}==${field.name}) @TableLogic #end private ${field.propertyType} ${field.propertyName}; #end ## ---------- END 字段循環遍歷 ---------- #if(!${entityLombokModel}) #foreach($field in ${table.fields}) #if(${field.propertyType.equals("boolean")}) #set($getprefix="is") #else #set($getprefix="get") #end public ${field.propertyType} ${getprefix}${field.capitalName}() { return ${field.propertyName}; } #if(${chainModel}) public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) { #else public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) { #end this.${field.propertyName} = ${field.propertyName}; #if(${chainModel}) return this; #end } #end ## --foreach end--- #end ## --end of #if(!${entityLombokModel})-- #if(${entityColumnConstant}) #foreach($field in ${table.fields}) public static final String ${field.name.toUpperCase()} = "${field.name}"; #end #end #if(${activeRecord}) @Override protected Serializable pkVal() { #if(${keyPropertyName}) return this.${keyPropertyName}; #else return null; #end } #end #if(!${entityLombokModel}) @Override public String toString() { return "${entity}{" + #foreach($field in ${table.fields}) #if($!{foreach.index}==0) "${field.propertyName}=" + ${field.propertyName} + #else ", ${field.propertyName}=" + ${field.propertyName} + #end #end "}"; } #end }
2、controller.java.vm
package ${package.Controller}; import org.springframework.web.bind.annotation.RequestMapping; #if(${restControllerStyle}) import org.springframework.web.bind.annotation.RestController; #else import org.springframework.stereotype.Controller; #end #if(${superControllerClassPackage}) import ${superControllerClassPackage}; #end /** * <p> * $!{table.comment} 前端控制器 * </p> * * @author ${author} * @since ${date} */ #if(${restControllerStyle}) @RestController #else @Controller #end @RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end") #if(${kotlin}) class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end #else #if(${superControllerClass}) public class ${table.controllerName} extends ${superControllerClass} { #else public class ${table.controllerName} { #end } #end
3、service.java.vm
package ${package.Service}; import ${package.Entity}.${entity}; import ${superServiceClassPackage}; /** * <p> * $!{table.comment} 服務類 * </p> * * @author ${author} * @since ${date} */ #if(${kotlin}) interface ${table.serviceName} : ${superServiceClass}<${entity}> #else public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { } #end
4、serviceImpl.java.vm
package ${package.ServiceImpl}; import ${package.Entity}.${entity}; import ${package.Mapper}.${table.mapperName}; import ${package.Service}.${table.serviceName}; import ${superServiceImplClassPackage}; import org.springframework.stereotype.Service; /** * <p> * $!{table.comment} 服務實現類 * </p> * * @author ${author} * @since ${date} */ @Service #if(${kotlin}) open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} { } #else public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} { } #end
5、mapper.java.vm
package ${package.Mapper}; import ${package.Entity}.${entity}; import ${superMapperClassPackage}; /** * <p> * $!{table.comment} Mapper 接口 * </p> * * @author ${author} * @since ${date} */ #if(${kotlin}) interface ${table.mapperName} : ${superMapperClass}<${entity}> #else public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { } #end
6、mapper.xml.vm
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="${package.Mapper}.${table.mapperName}"> #if(${enableCache}) <!-- 開啟二級緩存 --> <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/> #end #if(${baseResultMap}) <!-- 通用查詢映射結果 --> <resultMap id="BaseResultMap" type="${package.Entity}.${entity}"> #foreach($field in ${table.fields}) #if(${field.keyFlag})##生成主鍵排在第一位 <id column="${field.name}" property="${field.propertyName}" /> #end #end #foreach($field in ${table.commonFields})##生成公共字段 <result column="${field.name}" property="${field.propertyName}" /> #end #foreach($field in ${table.fields}) #if(!${field.keyFlag})##生成普通字段 <result column="${field.name}" property="${field.propertyName}" /> #end #end </resultMap> #end #if(${baseColumnList}) <!-- 通用查詢結果列 --> <sql id="Base_Column_List"> #foreach($field in ${table.commonFields}) ${field.columnName}, #end ${table.fieldNames} </sql> #end </mapper>
關於默認模板引擎,官方文檔說默認使用的是velocity,引用的依賴也是velocity,但在示例的代碼生成器CodeGenerator代碼中使用了freemarker的模板,需要把此行注掉,使用velocity

import java.util.ArrayList; import java.util.List; import java.util.Scanner; import org.apache.commons.lang3.StringUtils; 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.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.FileOutConfig; 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.TemplateConfig; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine; /** * 代碼生成器 */ public class CodeGenerator { public static void main(String[] args) { //所有配置參考:https://mp.baomidou.com/config/generator-config.html#entity // 代碼生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java/"); gc.setAuthor("pqx"); gc.setOpen(false); // gc.setSwagger2(true); 實體屬性 Swagger2 注解 //設置entity類的類名,%s為占位t符,即數據表轉換過來的名字,相應的還可以設置mapper,service等的名字 gc.setEntityName("%sPO"); gc.setControllerName("%sCtl"); mpg.setGlobalConfig(gc); // 數據源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:5711/dba_test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("username"); dsc.setPassword("pwd"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); //一個項目的話可以不用 // pc.setModuleName(scanner("模塊名")); pc.setParent("mybatisplus.springboot"); // 設置ctroller的包名、不設置默認為cotroller,相應的還可以設置entity等所有的包名 pc.setController("ctl"); 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().replace("PO", "") + "Mapper" + StringPool.DOT_XML; } }); /* cfg.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) { // 判斷自定義文件夾是否需要創建 checkDir("調用默認方法創建的目錄,自定義目錄用"); if (fileType == FileType.MAPPER) { // 已經生成 mapper 文件判斷存在,不想重新生成返回 false return !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(); // templateConfig.setController("templates/controller.java"); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); // strategy.setSuperEntityClass("你自己的父類實體,沒有就不用設置!"); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 公共父類 // strategy.setSuperControllerClass("你自己的父類控制器,沒有就不用設置!"); // 寫於父類中的公共字段 // strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("表名,多個英文逗號分割").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new VelocityTemplateEngine()); mpg.execute(); } /** * <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 + "!"); } }