mybatis-plus AutoGenerator 代码生成

本类无甚特殊,只是可以自定义生成模板 和 增加生成自定义文件

 

package net.firstelite.stgl.srv;

import cn.hutool.extra.template.engine.velocity.VelocityEngine;
import cn.hutool.extra.template.engine.velocity.VelocityTemplate;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
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.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import lombok.var;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;

public class CodeGenerator {
    public static void main(String[] args) {
        String tablePrefix = "t_";
        String projectName = "stgl";
        String databaseName = "stgl"; //数据库名
        String tableName = "t_society";//表名,多个英文逗号分割
        String projectPath = System.getProperty("user.dir") + "/smartcampus-submodule";
        String outDir = projectPath + File.separator + projectName;
        String url = "jdbc:postgresql://192.168.0.1:5432/" + databaseName + "?characterEncoding=utf-8&stringtype=unspecified";
        String driver = "org.postgresql.Driver";
        String username = "postgres";
        String password = "postgres";
        AutoGenerator generator = initConfig(outDir, url, driver, username, password, tableName, tablePrefix);
        create(generator, outDir, databaseName, projectName);
    }

    public static AutoGenerator initConfig(String outDir, String url, String driver, String username, String password, String tableName, String tablePrefix) {
        AutoGenerator generator = new AutoGenerator(); //代码生成器
        GlobalConfig gc = new GlobalConfig(); //全局策略配置
        DataSourceConfig ds = new DataSourceConfig();//数据源配置
        StrategyConfig strategy = new StrategyConfig();//数据库表配置
        /*---全局配置--*/
        gc.setOutputDir(outDir + "/src/main/java");
        gc.setFileOverride(true);//是否覆盖已存在文件
        gc.setDateType(DateType.ONLY_DATE);
        gc.setAuthor("Larry");
        gc.setOpen(false);
        gc.setSwagger2(true);
        //gc.setIdType(IdType.AUTO);//若表主键是uuid,用IdType.UUID
        generator.setGlobalConfig(gc);
        /*---数据源配置--*/
        ds.setDbType(DbType.POSTGRE_SQL);
        ds.setUrl(url);
        ds.setSchemaName("public");
        ds.setDriverName(driver);
        ds.setUsername(username);
        ds.setPassword(password);
        generator.setDataSource(ds);
        /*---数据库表配置--*/
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(tableName.split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(tablePrefix);
        generator.setStrategy(strategy);
        return generator;
    }

    public static void create(AutoGenerator generator, String outDir, String moduleName, String projectName) {
        PackageConfig pc = new PackageConfig();

        TemplateConfig templateConfig = new TemplateConfig();
        /*---包名配置--*/
        pc.setParent("net.firstelite." + projectName);
        pc.setEntity("model.entity." + moduleName);
        pc.setService("srv.service." + moduleName);
        pc.setServiceImpl("srv.service." + moduleName + ".impl");
        pc.setMapper("srv.mapper." + moduleName);
        pc.setXml("srv.mapper." + moduleName);
        pc.setController("web.controller." + moduleName);
        pc.setPathInfo(createPathInfo(outDir, projectName, moduleName, pc));
        generator.setPackageInfo(pc);
        templateConfig.setEntity("mytemplate\\Entity.java.vm")
                .setMapper(new TemplateConfig().getMapper())
                .setXml(new TemplateConfig().getXml())
                .setService(new TemplateConfig().getService())
                .setServiceImpl(new TemplateConfig().getServiceImpl())
                .setController(new TemplateConfig().getController());
        generator.setTemplate(templateConfig);
     generator.setCfg(getCustomConfig(outDir,pc)); generator.execute(); }
public static Map<String, String> createPathInfo(String outDir, String projectName, String moduleName, PackageConfig pc) { String dir = "src" + File.separator + "main" + File.separator + "java"; String mapperDir = "src" + File.separator + "main" + File.separator + "resources"; String entityPath = outDir + File.separator + projectName + "-model" + File.separator + dir + File.separator + convertPoint2FileSeparator(pc.getParent() + "." + pc.getEntity()); String mapperPath = outDir + File.separator + projectName + "-srv" + File.separator + dir + File.separator + convertPoint2FileSeparator(pc.getParent() + "." + pc.getMapper()); String xmlPath = outDir + File.separator + projectName + "-srv" + File.separator + mapperDir + File.separator + "sqlmapper" + File.separator + moduleName; String servicePath = outDir + File.separator + projectName + "-srv" + File.separator + dir + File.separator + convertPoint2FileSeparator(pc.getParent() + "." + pc.getService()); String serviceImplPath = outDir + File.separator + projectName + "-srv" + File.separator + dir + File.separator + convertPoint2FileSeparator(pc.getParent() + "." + pc.getServiceImpl()); String controllerPath = outDir + File.separator + projectName + "-web" + File.separator + dir + File.separator + convertPoint2FileSeparator(pc.getParent() + "." + pc.getController()); Map<String, String> pathInfo = new HashMap(6); pathInfo.put("entity_path", entityPath); pathInfo.put("mapper_path", mapperPath); pathInfo.put("xml_path", xmlPath); pathInfo.put("service_path", servicePath); pathInfo.put("service_impl_path", serviceImplPath); pathInfo.put("controller_path", controllerPath); return pathInfo; } public static String convertPoint2FileSeparator(String path) { path = path.replaceAll("\\.", Matcher.quoteReplacement(File.separator)); return path; } public static InjectionConfig getCustomConfig(String projectPath, PackageConfig pc) { // 自定义配置 var cfg = new InjectionConfig() { @Override public void initMap() { } }; // 如果模板引擎是 freemarker //String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 velocity, Entity.java.vm需要放到resources目录下,即资源目录下 String templatePath = "mytemplate\\Entity.java.vm"; // 自定义输出配置 var configList = new ArrayList<FileOutConfig>(); // 自定义配置会被优先输出 configList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! var result = projectPath + "/src/main/java/cn/java/" + pc.getModuleName() + "/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_JAVA;; return "*\\stgl\\model\\entity\\stgl\\Society.java"; } }); cfg.setFileOutConfigList(configList); return cfg; } }

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
        }

 

posted on 2022-04-24 16:19  空明流光  阅读(445)  评论(0编辑  收藏  举报

导航