Mybatis-Plus代码生成 3.5.1以下版本

Mybatis-Plus代码生成器(旧)

注意

适用版本:mybatis-plus-generator 3.5.1以下版本

关于为什么写旧版本生成器,因为新版本的一直出问题,还是旧版本舒服

依赖

        <!--oracle驱动-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>10.2.0.4.0</version>
        </dependency>
    
            <!-- mybatis-plus 增强CRUD -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <!-- mybatis-plus 代码生成器 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>mybatis-plus-extension</artifactId>
                    <groupId>com.baomidou</groupId>
                </exclusion>
            </exclusions>
        </dependency>
         <!-- 模板引擎依赖-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
        </dependency>
        <dependency>
            <groupId>com.ibeetl</groupId>
            <artifactId>beetl</artifactId>
            <version>3.9.3.RELEASE</version>
        </dependency>

生成器Java代码
代码参考https://gitee.com/ghlggc/mybatis-plus-code-generator/tree/master
再加上自己的一些习惯修改而成

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.AbstractTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Mybatis-plus 代码生成
 * @author lrq
 * @date 2022/1/4 16:11
 */
public class Generator {
    /** 包名:controller */
    public static final String PACKAGE_NAME_CONTROLLER = "controller";
    /** 文件名后缀:Controller */
    public static final String FILE_NAME_CONTROLLER = "%sController";

    /** 包名:service */
    public static final String PACKAGE_NAME_SERVICE = "service";
    /** 包名:service.impl */
    public static final String PACKAGE_NAME_SERVICE_IMPL = "service.impl";
    /** MP开头,Service结尾 */
    public static final String FILE_NAME_SERVICE = "I%sService";
    /** 文件名后缀:ServiceImpl */
    public static final String FILE_NAME_SERVICE_IMPL = "%sServiceImpl";

    /** 包名:model */
    public static final String PACKAGE_NAME_MODEL = "entity";
    /** 文件名后缀:Model */
    public static final String FILE_NAME_MODEL = "%sEntity";

    /** 包名:dao */
    public static final String PACKAGE_NAME_DAO = "mapper";
    /** 文件名后缀:Dao */
    public static final String FILE_NAME_DAO = "%sMapper";

    /** 目录名:xml */
    public static final String DIR_NAME_XML = "mapper";
    /** 文件名后缀:Mapper */
    public static final String FILE_NAME_XML = "%sMapper";

    /** 逻辑删除字段 */
    public static final String FIELD_LOGIC_DELETE_NAME = "delete_status";

    /** 乐观锁字段名 */
    public static final String FIELD_VERSION_NAME = "version";

    /** 作者 */
    public static final String AUTHOR = "Erwin Feng";

    /** 生成文件的输出目录 */
    public static String PROJECT_PATH = System.getProperty("user.dir");
    public static String MAIN_Path  = PROJECT_PATH + "/src/main/";

    /** 模板引擎。velocity / freemarker / beetl */
    public static final String TEMPLATE_ENGINE = "velocity";

    /** 是否支持Swagger,默认不支持 */
    public static final Boolean SWAGGER_SUPPORT = true;
    /**
     * 数据源配置
     * @param dbType 数据库类型
     * @param dbUrl 连接地址
     * @param username 用户名
     * @param password 密码
     * @param driver 驱动
     * @return DataSourceConfig
     */
    private static DataSourceConfig dataSourceConfig(DbType dbType, String dbUrl, String username, String password, String driver) {
        return new DataSourceConfig()
                .setDbType(dbType)
                .setUrl(dbUrl)
                .setUsername(username)
                .setPassword(password)
                .setDriverName(driver)
                ;
    }

    /**
     * 全局配置
     * @return
     */
    private static GlobalConfig globalConfig() {
        return new GlobalConfig()
                .setAuthor(AUTHOR)
                .setOutputDir(MAIN_Path)
                 // 是否覆盖已有文件
                .setFileOverride(true)
                 // 是否打开输出目录
                .setOpen(false)
                // 时间采用java 8,(操作工具类:JavaLib => DateTimeUtils)
                .setDateType(DateType.TIME_PACK)
                // 不需要ActiveRecord特性的请改为false
                .setActiveRecord(true)
                // XML 二级缓存
                .setEnableCache(true)
                // XML ResultMap
                .setBaseResultMap(true)
                // XML columList
                .setBaseColumnList(true)
                //是否生成
                .setKotlin(false)
                // 实体属性 Swagger2 注解,添加 Swagger 依赖,开启 Swagger2 模式(可选)
                .setSwagger2(SWAGGER_SUPPORT)
                // 自定义文件命名,注意 %s 会自动填充表实体属性!
                .setEntityName(FILE_NAME_MODEL)
                .setMapperName(FILE_NAME_DAO)
                .setXmlName(FILE_NAME_XML)
                .setServiceName(FILE_NAME_SERVICE)
                .setServiceImplName(FILE_NAME_SERVICE_IMPL)
                .setControllerName(FILE_NAME_CONTROLLER)
                // 主键类型
                .setIdType(IdType.ASSIGN_ID)
                ;
    }

    /**
     * 策略配置(数据库表配置)
     * @param tablePrefixes 表前缀(数组)
     * @param tableNames 表名
     * @param fieldPrefixes 字段前缀
     * @return
     */
    private static StrategyConfig strategyConfig(String [] tablePrefixes, String [] tableNames, String [] fieldPrefixes) {
        return new StrategyConfig()
                 // 全局大写命名 ORACLE 注意
                .setCapitalMode(true)
                 // 是否跳过视图
                .setSkipView(false)
                // 此处可以修改为您的表前缀(数组)
                .setTablePrefix(tablePrefixes)
                 // 字段前缀
                .setFieldPrefix(fieldPrefixes)
                 // 表名生成策略
                .setNaming(NamingStrategy.underline_to_camel)
                 // 字段名生成策略
                .setColumnNaming(NamingStrategy.underline_to_camel)
                //修改替换成你需要的表名,多个表名传数组
                .setInclude(tableNames)
                 // lombok实体
                .setEntityLombokModel(true)
                 // 配置 rest 风格的控制器(@RestController)
                .setRestControllerStyle(true)
                 // 【实体】是否生成字段常量(默认 false)// 可通过常量名获取数据库字段名 // 3.x支持lambda表达式
                .setEntityColumnConstant(false)
                 // 配置驼峰转连字符
                .setControllerMappingHyphenStyle(true)
                 // 逻辑删除属性名称
                .setLogicDeleteFieldName(FIELD_LOGIC_DELETE_NAME)
                 // 乐观锁字段名
                .setVersionFieldName(FIELD_VERSION_NAME)
                 // 开启实体字段注解
                .setEntityTableFieldAnnotationEnable(true)
                ;
    }

    /**
     *     包信息配置
     * @param packageName 包名
     * @param moduleName
     * @return
     */
    private static PackageConfig packageConfig(String packageName,String moduleName) {
        /*LinkedHashMap<String, String> pathInfo = new LinkedHashMap<>();
        pathInfo.put(ConstVal.ENTITY_PATH,MAIN_Path+"java/"+(packageName+"."+moduleName+"."+PACKAGE_NAME_MODEL).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.MAPPER_PATH,MAIN_Path+"java/"+(packageName+"."+moduleName+"."+PACKAGE_NAME_DAO).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.XML_PATH,MAIN_Path+"resources/"+(DIR_NAME_XML+"."+moduleName).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.SERVICE_PATH,MAIN_Path+"java/"+(packageName+"."+moduleName+"."+PACKAGE_NAME_SERVICE).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.SERVICE_IMPL_PATH,MAIN_Path+"java/"+(packageName+"."+moduleName+"."+PACKAGE_NAME_SERVICE_IMPL).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.CONTROLLER_PATH,MAIN_Path+"java/"+(packageName+"."+moduleName+"."+PACKAGE_NAME_CONTROLLER).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        */
        return new PackageConfig()
                .setParent(packageName)
                .setModuleName(moduleName)
                .setController(PACKAGE_NAME_CONTROLLER)
                .setEntity(PACKAGE_NAME_MODEL)
                .setMapper(PACKAGE_NAME_DAO)
                .setXml(DIR_NAME_XML)
                .setService(PACKAGE_NAME_SERVICE)
                .setServiceImpl(PACKAGE_NAME_SERVICE_IMPL)
//                .setPathInfo(pathInfo)
                ;
    }

    /**
     *
     * @param packageConfig
     * @return
     */
    private static InjectionConfig injectionConfig(final PackageConfig packageConfig) {
        InjectionConfig injectionConfig = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        List<FileOutConfig> fileOutConfigList = new ArrayList<FileOutConfig>();
        fileOutConfigList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                if (StringUtils.isEmpty(packageConfig.getModuleName())) {
                    return PROJECT_PATH + "/src/main/resources/mapper/" + tableInfo.getXmlName() + StringPool.DOT_XML;
                }else {
                    return PROJECT_PATH + "/src/main/resources/mapper/" + packageConfig.getModuleName() + "/" + tableInfo.getXmlName() + StringPool.DOT_XML;
                }
            }
        });
        injectionConfig.setFileOutConfigList(fileOutConfigList);
        return injectionConfig;
    }

    /**
     * 获取模板引擎
     * @return 模板引擎 {@link AbstractTemplateEngine}
     */
    private static AbstractTemplateEngine getTemplateEngine() {
        switch (TEMPLATE_ENGINE) {
            case "velocity":
                return new VelocityTemplateEngine();
            case "freemarker":
                return new FreemarkerTemplateEngine();
            case "beetl":
                return new BeetlTemplateEngine();
            default:
                return new VelocityTemplateEngine();
        }
    }

    /**
     * 执行器
     * @param dbType
     * @param dbUrl
     * @param username
     * @param password
     * @param driver
     * @param tablePrefixes
     * @param tableNames
     * @param packageName
     */
    public static void execute(DbType dbType, String dbUrl, String username, String password, String driver,
                               String [] tablePrefixes, String [] tableNames, String packageName,String moduleName, String [] fieldPrefixes) {
        PackageConfig packageInfo = packageConfig(packageName, moduleName);
        new AutoGenerator()
                .setGlobalConfig(globalConfig())
                .setDataSource(dataSourceConfig(dbType, dbUrl, username, password, driver))
                .setStrategy(strategyConfig(tablePrefixes, tableNames, fieldPrefixes))
                .setPackageInfo(packageInfo)
                .setTemplateEngine(getTemplateEngine())
                .setCfg(injectionConfig(packageInfo))
                .execute();
    }

    public static void main(String[] args) {
        DbType dbType = DbType.ORACLE;
        String dbUrl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
        String username = "username";
        String password = "password";
        String driver = "oracle.jdbc.OracleDriver";
        // 表前缀,生成的实体类,不含前缀
        String [] tablePrefixes = {};
        // 表名,为空,生成所有的表
        String [] tableNames = {"tableNames1","tableNames2"};
        for (int i = 0; i < tableNames.length; i++) {
            tableNames[i] = tableNames[i].toUpperCase(Locale.ROOT);
        }
        // 字段前缀
        String [] fieldPrefixes = {};
        // 基础包名
        String packageName = "com.rrr";
        String moduleName = "";
        execute(dbType, dbUrl, username, password, driver, tablePrefixes, tableNames, packageName,moduleName, fieldPrefixes);
    }
}
上一篇:【Java教程】Java 生成器模式


下一篇:vue父组件在接收子组件方法传递参数的时,如何添加自定义参数