自定义属性注入到模板

注意:本教程使用的数据库脚本、数据模型和环境信息请参考 “MyBatis Plus环境准备” 章节,点击下载示例源码

上一章节介绍了自定义代码生成器模板,本章节将介绍怎样自定义属性,且将该属性注入到模板中,在模板中可以使用 ${} 方法进行使用。注入自定义属性简单简略代码如下:

(1)继承 InjectionConfig 抽象类,重写 initMap 方法,创建一个 Map<String,Object> 对象作为参数调用 setMap 方法。代码如下:

// 配置自定义属性注入
InjectionConfig injectionConfig = new InjectionConfig() {
    // 自定义属性注入,向自定义的模板中注入 my_field 属性
    // 通过 ${cfg.my_field} 获取属性之
    @Override
    public void initMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("my_field", "你好!这是我自己注入的属性哦");
        this.setMap(map);
    }
};
mpg.setCfg(injectionConfig);

(2)在自定义的模板中使用 ${cfg.my_field} 方式进行引用。代码如下:

package ${package.Entity};

/**
 * 自定义模板 - ${cfg.my_field}
 * @author ${author}
 * @since ${date}
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class ${entity} implements Serializable {
    private static final long serialVersionUID = 1L;
<#-- ----------  BEGIN 字段循环遍历  ---------->
<#list table.fields as field>
    private ${field.propertyType} ${field.propertyName};
</#list>
<#------------  END 字段循环遍历  ---------->
}

示例代码

(1)自定义模板 entity3.java.ftl 内容如下:

package ${package.Entity};

/**
 * 自定义模板 - ${cfg.my_field}
 * @author ${author}
 * @since ${date}
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class ${entity} implements Serializable {
    private static final long serialVersionUID = 1L;
<#-- ----------  BEGIN 字段循环遍历  ---------->
<#list table.fields as field>
    private ${field.propertyType} ${field.propertyName};
</#list>
<#------------  END 字段循环遍历  ---------->
}

该模板位于 templates/entity3.java.ftl 处。

(2)客户端代码如下:

package com.hxstrive.mybatis_plus.generator.demo3;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义模板可以参考 MyBatis Plus 内置模板,位置:
 * mybatis-plus-generator-3.4.0.jar 文件的 templates 目录下面
 */
public class MysqlGenerator {
    public static void main(String[] args) {
        String userDir = System.getProperty("user.dir");
        System.out.println("userDir=" + userDir);
        
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/mybatis-plus-learn/src/main/java");
        gc.setAuthor("hxstrive"); // 作者名称
        gc.setBaseResultMap(true); // mapper.xml 生成 ResultMap
        gc.setBaseColumnList(true); // mapper.xml 生成 ColumnList
        gc.setOpen(false);
        mpg.setGlobalConfig(gc);
        
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_test?useSSL=false");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("aaaaaa");
        mpg.setDataSource(dsc);
        
        // 配置自定义属性注入
        InjectionConfig injectionConfig = new InjectionConfig() {
            // 自定义属性注入,向自定义的模板中注入 my_field 属性
            // 通过 ${cfg.my_field} 获取属性之
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
                map.put("my_field", "你好!这是我自己注入的属性哦");
                this.setMap(map);
            }
        };
        mpg.setCfg(injectionConfig);
        
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.hxstrive.mybatis_plus.auto");
        mpg.setPackageInfo(pc);
        
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setEntity("templates/entity3.java");
        mpg.setTemplate(templateConfig);
        
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude("user");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

上面代码中,我们将自定义的 “my_field=你好!这是我自己注入的属性哦” 键值对注入到自定义模板,在模板中可以通过 ${cfg.my_field} 方式引用自定义的属性。成功运行客户端代码后,User.java 效果代码如下:

package com.hxstrive.mybatis_plus.auto.entity;

/**
 * 自定义模板 - 你好!这是我自己注入的属性哦
 * @author hxstrive
 * @since 2020-09-27
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer userId;
    private String name;
    private String sex;
    private Integer age;
    private Blob face;
    private Double salary;
    private LocalDate borthday;
}

说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号