mybatis-plus-generator 模板生成代码

Posted yako

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis-plus-generator 模板生成代码相关的知识,希望对你有一定的参考价值。

maven:

 <dependencies>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.29</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.26</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.26</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

java(CodeGenerator):

package com.youlan;

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.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
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) 


        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("terry.qian");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);
        gc.setEntityName("%sModel");

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://192.168.1.104:3306/freport?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("com.baomidou.ant");
        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() 
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) 
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录");
                return false;
            
        );
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setEntity("templates/custommodel");
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.deloitte.freport.dbase.IEntity");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);

        // 公共父类
        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    

 

freemarker(custommodel.ftl):

package $package.Entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import java.util.Date;
import com.deloitte.freport.annotation.QuotaCodeAnn
import com.deloitte.freport.enums.QuotaEnum;
<#assign xxx = ["mi_business_type_l3","mi_business_type_l2","sub_channel_l2","distribution_channel_l3","distribution_channel_l2","insurance_type_l3","insurance_type_l2","type","product_type","business_type_l3","business_type_l2","business_type_l4","higher_product_level","medical_insurance_type","business_type_l3","create_time","last_changed","settled_time","status", "org_type", "org","business_type_merge","insurance_type_l4","business_type_merge"]/>

<#list table.importPackages as pkg>
import $pkg;
</#list>
<#if entityLombokModel>

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if>

/**
 * <p>
 * <#if table.comment??>$table.comment</#if>
 * </p>
 *
 * @table $table.name
 * @author $author
 * @since $date
 */
<#if entityLombokModel>
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
</#if>
<#if superEntityClass??>
public class $entity implements $superEntityClass<#if activeRecord><$entity></#if> 
<#elseif activeRecord>
public class $entity extends Model<$entity> 
<#else>
public class $entity implements Serializable 
</#if>

    private static final long serialVersionUID = 1L;
<#-- ----------  BEGIN 字段循环遍历  ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="$field.propertyName"/>
</#if>

<#if field.comment!?length gt 0>
    /**
     * $field.comment
     */
</#if>
<#if field.keyFlag>
<#-- 主键 -->
<#if field.keyIdentityFlag>
    @TableId(value = "$field.name", type = IdType.AUTO)
<#elseif idType??>
    @TableId(value = "$field.name", type = IdType.$idType)
<#elseif field.convert>
    @TableId("$field.name")
</#if>
<#-- 普通字段 -->
<#elseif field.fill??>
<#-- -----   存在字段填充设置   ----->
<#if field.convert>
    @TableField(value = "$field.name", fill = FieldFill.$field.fill)
<#else>
    @TableField(fill = FieldFill.$field.fill)
</#if>
<#elseif field.convert>
    @TableField("$field.name")
</#if>
<#-- 乐观锁注解 -->
<#if versionFieldName!"" == field.name>
    @Version
</#if>
<#-- 逻辑删除注解 -->
<#if logicDeleteFieldName!"" == field.name>
    @TableLogic
</#if>
<#if xxx?seq_contains(field.name)>
    @Column(column = "$field.name")
    private $field.propertyType $field.propertyName;
<#else>
    @Column(column = "$field.name")
    @QuotaCodeAnn(codeEnum = QuotaEnum.$field.name)
    private $field.propertyType $field.propertyName;
</#if>
</#list>
<#------------  END 字段循环遍历  ---------->

<#if !entityLombokModel>
<#list table.fields as field>
<#if field.propertyType == "boolean">
    <#assign getprefix="is"/>
<#else>
    <#assign getprefix="get"/>
</#if>
    public $field.propertyType $getprefix$field.capitalName() 
        return $field.propertyName;
    

<#if entityBuilderModel>
    public $entity set$field.capitalName($field.propertyType $field.propertyName) 
<#else>
    public void set$field.capitalName($field.propertyType $field.propertyName) 
</#if>
        this.$field.propertyName = $field.propertyName;
<#if entityBuilderModel>
        return this;
</#if>
    
</#list>
</#if>

<#if entityColumnConstant>
<#list table.fields as field>
    public static final String $field.name?upper_case = "$field.name";

</#list>
</#if>
<#if activeRecord>
    @Override
    protected Serializable pkVal() 
<#if keyPropertyName??>
        return this.$keyPropertyName;
<#else>
        return this.id;
</#if>
    

</#if>
<#if !entityLombokModel>
    @Override
    public String toString() 
        return "$entity" +
<#list table.fields as field>
<#if field_index==0>
        "$field.propertyName=" + $field.propertyName +
<#else>
        ", $field.propertyName=" + $field.propertyName +
</#if>
</#list>
        "";
    
</#if>

 

以上是关于mybatis-plus-generator 模板生成代码的主要内容,如果未能解决你的问题,请参考以下文章

springboot+mybatis-plus-generator3.5.1代码生产

mybatis-plus-generator的使用

代码生成器

Mybatis-plus 基础使用

mybais-plus整合springboot,自动代码生成。

AutoGenerator