mybatis-plus代码生成器以及自定义vm模板使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39089503/article/details/90779797

1.pom.xml

<mybatis.version>3.1.1</mybatis.version>
<!-- mybatis-plus -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatis.version}</version>
</dependency>
<!--3.0.3版本后需要手动添加生成器和模板-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>${mybatis.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>${velocity.version}</version>
</dependency>

2.MpGenerator文件

package org.zhd.data.provider.utils;

import com.baomidou.mybatisplus.annotation.IdType;
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.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.springframework.context.annotation.Profile;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cth
 * @date 2019/06/03
 */
@Profile("test")
public class MpGenerator {
    public static void main(String[] args) {
        AutoGenerator mpg = new AutoGenerator();
        String prefix = "Dept";
        String tableName = "basic_dept";

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        // 生成文件的输出目录
        gc.setOutputDir(projectPath + "/src/main/java");
        // 作者
        gc.setAuthor("cth");
        // 生成后打开目录
        gc.setOpen(false);
        // 设置时间类型使用哪个包下的
        gc.setDateType(DateType.ONLY_DATE);
        // 文件命名方式
        gc.setMapperName(prefix + "Mapper");
        gc.setEntityName(prefix + "Bean");
        gc.setControllerName(prefix + "Controller");
        gc.setServiceName(prefix + "Service");
        // 主键策略
        gc.setIdType(IdType.INPUT);
        //实体属性 Swagger2 注解
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:oracle:thin:@ip:1521/orcl");
        dsc.setDriverName("oracle.jdbc.driver.OracleDriver");
        dsc.setUsername("jszhd");
        dsc.setPassword("jszhd");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("org.zhd.data.provider")
                .setEntity("entity")
                .setMapper("mapper")
                .setController("controller.basic")
                .setService("service");
        mpg.setPackageInfo(pc);

        //配置自定义属性注入
        InjectionConfig injectionConfig = new InjectionConfig() {
            //.vm模板中,通过${cfg.abc}获取属性
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
//                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                map.put("abc", "自定义属性描述");
                this.setMap(map);
            }
        };
        mpg.setCfg(injectionConfig);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        // 使用自定义模板,不想要生成就设置为null,如果不设置null会使用默认模板
        templateConfig.setEntity("templates/entity2.java");
        templateConfig.setController("templates/controller2.java");
        templateConfig.setMapper("templates/mapper2.java");
        templateConfig.setService("templates/service2.java");
        templateConfig.setServiceImpl(null);
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // 使用lombok
        strategy.setEntityLombokModel(true);
        strategy.setInclude(tableName.toUpperCase());
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        mpg.execute();
    }

}

3.自定义模板
模板位置:
在这里插入图片描述
entity2.java.vm 自定义模板
velocity语法参考:(转)

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;
#end
import com.baomidou.mybatisplus.annotation.KeySequence;
import com.baomidou.mybatisplus.annotation.FieldFill;

## 表备注,作者,日期
/**
 * $!{table.comment}
 * @author ${author}
 * @since ${date}
 */
## 使用lombok
#if(${entityLombokModel})
@Data
#end
## 有NamingStrategy为true
#if(${table.convert})
@TableName("${table.name}")
#end
## 用的oracle需要KeySequence
@KeySequence(value = "${table.name}_SEQ")
## swagger2
#if(${swagger2})
@ApiModel(value="${entity}对象")
#end
public class ${entity} implements Serializable {

## ----------  BEGIN 字段循环遍历  ----------
#foreach($field in ${table.fields})
## 主键策略
#if(${field.keyFlag})
#if(${field.keyIdentityFlag})
    @TableId(value = "${field.name}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
    @TableId(value = "${field.name}", type = IdType.${idType})
#elseif(${field.convert})
    @TableId("${field.name}")
#end
#end
## 自动填充
#if(${field.propertyName} == "dataUpdatedate")
    @TableField(fill = FieldFill.UPDATE)
#end
## swagger2字段api
#if("$!field.comment" != "")
#if(${swagger2})
#if(${field.propertyType} == "Long" || ${field.propertyType} == "Integer")
#if(${field.keyFlag})
    @ApiModelProperty(value = "${field.comment},新增不传",example="1")
#else
    @ApiModelProperty(value = "${field.comment}",example="1")
#end
#else
    @ApiModelProperty(value = "${field.comment}")
#end
#end
#end
    private ${field.propertyType} ${field.propertyName};

#end
## ----------  END 字段循环遍历  ----------
## ---------- 使用的lombok,所以后面的get/set都不要 ---------------
}

4.运行MpGenerator main函数

猜你喜欢

转载自blog.csdn.net/qq_39089503/article/details/90779797