• MyBatis-Plus代码生成器官方默认模板(vm)


    模板引擎是 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 + "!");
        }
    }
    自用CodeGenerator,在官方示例上稍作修改,增加了部分自己的设置
  • 相关阅读:
    我的Ajax之旅(一):不能加载'AjaxControlToolkit'。。。拒绝访问
    网络编程(一):用C#下载网络文件的2种方法
    Locks
    Threads
    C语言中函数名和struct名可以重名!
    使用#include <pthread.h>
    APUE Chapter 7 (2)main函数的参数
    Creating a shared and static library with the gnu compiler [gcc][转]
    Signals
    APUE Chapter 7(3) – Memory layout of a C program
  • 原文地址:https://www.cnblogs.com/aland-1415/p/12979440.html
Copyright © 2020-2023  润新知