MybatisPlus代码生成器配置(处理blob等类型)

一:新建springboot项目

二:导包

<dependencies>
  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.3.2</version>
  </dependency>
  <dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.2</version>
  </dependency>
  <dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
  </dependency>
  <dependency>
    <groupId>com.ibeetl</groupId>
    <artifactId>beetl</artifactId>
    <version>3.1.8.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.20</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.25</version>
    <scope>compile</scope>
  </dependency>
</dependencies>

三:复制相应的模板到\resources\templates目录下

以下为模板链接

mybatis-plus/mybatis-plus-generator/src/main at 3.0 · baomidou/mybatis-plus · GitHub

 

 entity.java.vm文件如下

package ${package.Entity};

#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#if(${entityLombokModel})
import lombok.Data;
import lombok.EqualsAndHashCode;
##import lombok.experimental.Accessors;
#end

/**
 * @Description:$!{table.comment}
 * @author ${author}
 * @since ${date}
 */
@ApiModel(value ="$!{table.comment}")
#if(${entityLombokModel})
@Data
#if(${superEntityClass})
@EqualsAndHashCode(callSuper = true)
#else
@EqualsAndHashCode(callSuper = false)
#end
##@Accessors(chain = true)
#end
#if(${table.convert})
@TableName("${table.name}")
#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

    private static final long serialVersionUID = 1L;

## ----------  BEGIN 字段循环遍历  ----------
#foreach($field in ${table.fields})
    #if(${field.keyFlag})
        #set($keyPropertyName=${field.propertyName})
    #end
    #if("$!field.comment" != "")
    @ApiModelProperty(value = "${field.comment}")
    #end
    #if(${field.keyFlag})
    ## 主键s
    #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
    ## 普通字段
    #elseif(${field.fill})
    ## -----   存在字段填充设置   -----
        #if(${field.convert})
        @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
        #else
        @TableField(fill = FieldFill.${field.fill})
        #end
    #elseif(${field.convert})
    @TableField("${field.name}")
    #else
    @TableField("${field.name}")
    #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(${entityBuilderModel})
        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(${entityBuilderModel})
                return this;
        #end
        }
    #end
#end

#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($!{velocityCount}==1)
                "${field.propertyName}=" + ${field.propertyName} +
        #else
                ", ${field.propertyName}=" + ${field.propertyName} +
        #end
    #end
        "}";
    }
#end
}

四:生成策略,main方法


import com.baomidou.mybatisplus.annotation.DbType;
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.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

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();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        final String projectPath = System.getProperty("user.dir");
//        gc.setOutputDir(projectPath + "/src/main/java");//输出文件路径
        gc.setOutputDir(projectPath + "/idp-mybatis-plus-generator/codeGenerate");//输出文件路径
//        gc.setOutputDir(projectPath + "/pds-api/src/main/java");//输出文件路径
        gc.setFileOverride(true); // 是否文件覆盖
        gc.setActiveRecord(false);// 不需要ActiveRecord(实体类继承Model)特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML ColumnList
        gc.setEntityName("%s");
        gc.setAuthor("zz");// 作者

        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setControllerName("%sController");
        // 默认service接口名IXXXService 自定义指定之后就不会用I开头了
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        //gc.setXmlName("%sMapper");
        //设置日期格式,默认格式为 LocalDateTime 和 LocalDate
        gc.setDateType(DateType.ONLY_DATE);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        // 自定义数据库表字段类型转换
        dsc.setTypeConvert((GlobalConfig gc2,String fieldType) -> {
            String t = fieldType;
            if (t.contains("char") || t.contains("text")) {
                return DbColumnType.STRING;
            } else if (t.contains("bigint")) {
                return DbColumnType.LONG;
            } else if (t.contains("int")) {
                return DbColumnType.INTEGER;
            } else if (t.contains("date") || t.contains("time") || t.contains("year")) {
                return DbColumnType.DATE;
            } else if (t.contains("text")) {
                return DbColumnType.STRING;
            } else if (t.contains("bit")) {
                return DbColumnType.BOOLEAN;
            } else if (t.contains("decimal")) {
                return DbColumnType.BIG_DECIMAL;
            } else if (t.contains("clob")) {
                return DbColumnType.STRING;
            } else if (t.contains("blob")) {
                return DbColumnType.STRING;
            } else if (t.contains("binary")) {
                return DbColumnType.BYTE_ARRAY;
            } else if (t.contains("float")) {
                return DbColumnType.FLOAT;
            } else if (t.contains("double")) {
                return DbColumnType.DOUBLE;
            } else if (t.contains("json") || t.contains("enum")) {
                return DbColumnType.STRING;
            }
            return DbColumnType.STRING;
        });
        dsc.setDbType(DbType.MYSQL);
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("xxx");
        dsc.setPassword("xxx");
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&characterEncoding=utf-8");
        mpg.setDataSource(dsc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        String templatePath = "/templates/mapper.xml.vm"; // Velocity模板
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                String result = projectPath + "/idp-mybatis-plus-generator/codeGenerate/resources/mappings/pds"
//                        + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                return result;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig tc = new TemplateConfig();
        // templates/entity.java 模板路径配置,默认在templates目录下,.vm 后缀不用加
        tc.setEntity("templates/entity.java");//使用自定义模板生成实体类
        tc.setXml("");
        mpg.setTemplate(tc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setEntityLombokModel(true);
        strategy.setEntitySerialVersionUID(true);
        strategy.setRestControllerStyle(true);
        //strategy.setTablePrefix(new String[]{"fac_"});// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略(下划线转驼峰)
        strategy.setSuperControllerClass("com.hnac.hzsidp.pds.web.CommonController");
        //strategy.setSuperEntityClass(PrecBaseInfo.class);
        //strategy.setSuperEntityColumns("id", "create_user", "create_dept", "create_time", "update_user", "update_time", "status", "is_deleted");
        //strategy.setSuperEntityColumns("name", "info");
        strategy.setInclude("author_scope_api", "author_user"); // 需要生成的表名

        strategy.setSuperMapperClass(null);

        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.hnac.hzsidp.pds");
        pc.setController("web");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setMapper("dao");
        pc.setEntity("entity");
        pc.setXml("xml");
        mpg.setPackageInfo(pc);

        // 执行生成
        mpg.execute();

    }

}

猜你喜欢

转载自blog.csdn.net/zzchances/article/details/128444969