mybatisPlus代码生成器

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以根据模板快速生成代码,方便前后端的工作。

  1. 添加代码生成器依赖
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.0</version>
</dependency>
  1. 添加模板引擎依赖
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
</dependency>

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
...

  1. 编写配置
  • 配置 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");
  1. 自定义代码模板
//指定自定义模板路径, 位置:/resources/templates/entity2.java.ftl(或者是.vm)
//注意不要带上.ftl(或者是.vm), 会根据使用的模板引擎自动识别
TemplateConfig templateConfig = new TemplateConfig()
    .setEntity("templates/entity2.java");

AutoGenerator mpg = new AutoGenerator();
//配置自定义模板
mpg.setTemplate(templateConfig);
  1. 自定义属性注入
InjectionConfig injectionConfig = new InjectionConfig() {
    //自定义属性注入:abc
    //在.ftl(或者是.vm)模板中,通过${cfg.abc}获取属性
    @Override
    public void initMap() {
        Map<String, Object> map = 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}
  1. 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.</br>  
#end
this is 2.
this is 1.
this is 0.
this is -1.
this is -2
  • 条件
#if(condition)  
......
#elseif(condition)  
......
#else  
......
#end 
  • 关系和逻辑操作符
&& 并且  || 或者   ! 取反
  • 注释
##单行注释

#*  
    多行的注释
*#  
  1. demo
  • spring-boot-plus代码生成器入口类
package test;

/**
 * spring-boot-plus代码生成器入口类
 *
 **/
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;

/**
* spring-boot-plus代码生成器
*
* @author geekidea
* @date 2018-11-08
*/
@Data
@Accessors(chain = true)
public class CodeGenerator {

   /**
    * 用户名
    */
   private String userName;
   /**
    * 密码
    */
   private String password;
   /**
    * 驱动名称
    */
   private String driverName;
   /**
    * 驱动URL
    */
   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";
   /**
    * 代码生成策略 true:All/false:SIMPLE
    * 0. SIMPLE 生成最基本的代码
    * 1. NORMAL 生成普通代码
    * 2. ALL 生成所有的代码
    */
   private GeneratorStrategy generatorStrategy = GeneratorStrategy.ALL;


   /**
    * 生成策略
    */
   public enum GeneratorStrategy {
       SIMPLE, NORMAL, ALL
   }

   /**
    * 分页列表查询是否排序 true:有排序参数/false:无
    */
   private boolean pageListOrder = false;
   /**
    * 是否生成validation校验,true:生成/false:不生成
    */
   private boolean paramValidation = true;

   /**
    * 是否生成实体类
    */
   private boolean generatorEntity;
   /**
    * 是否生成控制器
    */
   private boolean generatorController;
   /**
    * 是否生成service接口
    */
   private boolean generatorService;
   /**
    * 是否生成service实现类
    */
   private boolean generatorServiceImpl;
   /**
    * 是否生成Mapper
    */
   private boolean generatorMapper;
   /**
    * 是否生成Mapper XML
    */
   private boolean generatorMapperXml;

   private boolean generatiorEvent;
   /**
    * 是否生成列表页
    */
   private boolean generatorListHtml;
   /**
    * 是否生成列编辑页
    */
   private boolean generatorEditHtml;

   private boolean generatorActivitiTable;
   /**
    * 是否生成查询参数
    */
   private boolean generatorQueryParam;
   /**
    * 是否生成查询VO
    */
   private boolean generatorQueryVo;
   /**
    * 是否生成Shiro RequiresPermissions 注解
    */
   private boolean requiresPermissions;
   /**
    * 是否生成mock的Js文件
    */
   private boolean mockJs;
   /**
    * 是否生成接口的js文件
    */
   private boolean interfaceJs;
   // ############################ 自定义配置部分 end ############################

   /**
    * 公共父包
    */
   private String commonParentPackage;
   /**
    * 公共的mybatis包
    */
   private String mybatisParentPackage;

   /**
    * 实体父类
    */
   private String superEntity;
   /**
    * 控制器父类
    */
   private String superController;
   /**
    * service父接口
    */
   private String superService;
   /**
    * service实现父类
    */
   private String superServiceImpl;
   /**
    * 查询参数父类
    */
   private String superQueryParam;
   /**
    * 实体父类实体列表
    */
   private String[] superEntityCommonColumns;

   // 公共类包路径
   /**
    * 公共id参数路径
    */
   private String commonIdParam;
   /**
    * 公共结果集路径
    */
   private String commonApiResult;
   /**
    * 公共排序枚举
    */
   private String commonOrderEnum;
   /**
    * 公共排序查询参数
    */
   private String commonOrderQueryParam;
   /**
    * 公共分页对象
    */
   private String commonPaging;

   /**
    * 是否文件覆盖
    */
   private boolean fileOverride;

    // 自定义需要填充的字段
    private  List<TableFill> 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);

               Map<String, Object> map = 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<FileOutConfig> 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);

       /**
        * 注意,根据实际情况,进行设置
        * 当表名称的前缀和模块名称一样时,会去掉表的前缀
        * 比如模块名称为user,表明为user_info,则生成的实体名称是Info.java,一定要注意
        */
       //strategy.setTablePrefix(pc.getModuleName() + "_");
       mpg.setStrategy(strategy);
       mpg.execute();
   }

   /**
    * 下划线专程驼峰命名
    * sys_user --> sysUser
    *
    * @param underline
    * @return
    */
   public static String underlineToCamel(String underline) {
       if (StringUtils.isNotBlank(underline)) {
           return NamingStrategy.underlineToCamel(underline);
       }
       return null;
   }

   /**
    * 下划线转换成帕斯卡命名
    * sys_user --> SysUser
    *
    * @param underline
    * @return
    */
   public static String underlineToPascal(String underline) {
       if (StringUtils.isNotBlank(underline)) {
           return NamingStrategy.capitalFirst(NamingStrategy.underlineToCamel(underline));
       }
       return null;
   }

   /**
    * 下划线转换成冒号连接命名
    * sys_user --> sys:user
    *
    * @param underline
    * @return
    */
   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"));
   }


}

  • 自定义模板
<template>
    <el-dialog :visible.sync="visible" :title="title" width="800px" @close="onClose">
        <el-form
                ref="dataForm"
                :rules="rules"
                :model="${cfg.tableName}Data"
                label-width="100px"
                style="width: 500px; margin: auto"
                class="sinosoft-ruleForm"
        >
        #foreach($field in ${table.fields})
        <el-form-item label="$!{field.comment}" prop="${field.propertyName}">
          <el-input v-model="${cfg.tableName}Data.${field.propertyName}" clearable placeholder="$!{field.comment}" />
        </el-form-item>
        #end
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: right">
            <el-button type="danger" @click="onClose"> 取消 </el-button>
            <el-button type="primary" @click="onSubmit"> 确定 </el-button>
        </div>
    </el-dialog>
</template>
<script>

    import { add${cfg.TableName}, update${cfg.TableName} } from "@/api/模块名称-${cfg.tableName}";
    export default {
        data() {
            return {
                visible: false,
                title: "",
                ${cfg.tableName}Data: {
                    #foreach($field in ${table.fields})
                        ${field.propertyName}:'',
                    #end
                },
                disabled: false,
                rules: {
                    #foreach($field in ${table.fields})
                        ${field.propertyName}: [{required: true, message: "$!{field.comment}", trigger: "blur" }],
                    #end
                }

        };
        },
        methods: {
            add() {
                this.visible = true;
                this.title = "新增$!{table.comment}";
                this.disabled = false;
            },
            edit(record) {
                this.disabled = true;
                this.visible = true;
                this.title = "编辑$!{table.comment}";
                this.${cfg.tableName}Data = Object.assign({}, record);
                console.log("编辑$!{table.comment}", this.roleData);
            },
            // 提交
            onSubmit() {
                if (this.${cfg.tableName}Data.id) {
                    console.log("编辑参数", this.${cfg.tableName}Data);
                    update${cfg.TableName}(this.${cfg.tableName}Data).then((res) => {
                        if (res.code === 200) {
                            this.$\message.success(res.msg);
                            this.onClose();
                            this.$\emit("getList"); //刷新数据
                        } else {
                            this.$\message.warning(res.msg);
                        }
                    })
                }else{
                    add${cfg.TableName}(this.${cfg.tableName}Data).then((res) => {
                        if (res.code === 200) {
                            this.$\message.success(res.msg);
                            this.onClose();
                            this.$\emit("getList"); //刷新数据
                        } else {
                            this.$\message.warning(res.msg);
                        }
                    });
                }
            },
            //关闭按钮(请清空相关数据)
            onClose() {
                this.${cfg.tableName}Data = {};
                this.visible = false;
                this.$nextTick(() => {
                    this.$refs["dataForm"].clearValidate(); //清空校验信息
                });
            },
        }
    };
</script>
<style lang="scss" scoped>

</style>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值