All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.zodiac.develop.support.PlatformCodeGenerator Maven / Gradle / Ivy

package org.zodiac.develop.support;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.converts.OracleTypeConvert;
import com.baomidou.mybatisplus.generator.config.converts.PostgreSqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.converts.SqlServerTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.zodiac.commons.constants.SystemPropertiesConstants;
import org.zodiac.commons.util.Func;
import org.zodiac.commons.util.spring.Springs;
import org.zodiac.develop.constants.DevelopConstants;
import org.zodiac.mybatisplus.config.MyBatisPlusGeneratorConfigInfo;
import org.zodiac.mybatisplus.util.MyBatisPlusUtil;
import org.zodiac.sdk.mime.MimeMappings;
import org.zodiac.sdk.toolkit.util.ExceptionUtil;
import org.zodiac.sdk.toolkit.util.lang.ObjUtil;
import org.zodiac.sdk.toolkit.util.lang.StrUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 代码生成器配置类。
 *
 */
public class PlatformCodeGenerator {

    private static Logger log = LoggerFactory.getLogger(PlatformCodeGenerator.class);

    /**
     * 代码所在系统
     */
    private String systemName = DevelopConstants.SWORD_NAME;
    /**
     * 代码模块名称
     */
    private String codeName;
    /**
     * 代码所在服务名
     */
    private String serviceName = "platform-service";
    /**
     * 代码生成的包名
     */
    private String packageName = "org.zodiac.test";
    /**
     * 代码后端生成的地址
     */
    private String packageDir;
    /**
     * 代码前端生成的地址
     */
    private String packageWebDir;
    /**
     * 需要去掉的表前缀
     */
    private String[] tablePrefix = {"t_platform_"};
    /**
     * 需要生成的表名(两者只能取其一)
     */
    private String[] includeTables = {"t_platform_test"};
    /**
     * 需要排除的表名(两者只能取其一)
     */
    private String[] excludeTables = {};
    /**
     * 是否包含基础业务字段
     */
    private boolean hasSuperEntity = false;
    /**
     * 是否包含包装器
     */
    private boolean hasWrapper = false;
    /**
     * 基础业务字段
     */
    private String[] superEntityColumns =
        {"id", "create_time", "create_user", "create_dept", "update_time", "update_user", "status", "is_deleted"};
    /**
     * 租户字段
     */
    private String tenantColumn = "tenant_id";
    /**
     * 是否启用swagger
     */
    private boolean swagger2 = true;
    /**
     * 数据库驱动名
     */
    private String driverName;
    /**
     * 数据库链接地址
     */
    private String url;
    /**
     * 数据库用户名
     */
    private String username;
    /**
     * 数据库密码
     */
    private String password;

    private final DbType dbType;
    private final MyBatisPlusGeneratorConfigInfo myBatisPlusGeneratorConfigInfo;

    public PlatformCodeGenerator() {
        this(null, null);
    }

    public PlatformCodeGenerator(DbType dbType, MyBatisPlusGeneratorConfigInfo myBatisPlusGeneratorConfigInfo) {
        this.dbType = dbType;
        this.myBatisPlusGeneratorConfigInfo = myBatisPlusGeneratorConfigInfo;
    }

    public String getSystemName() {
        return systemName;
    }

    public PlatformCodeGenerator setSystemName(String systemName) {
        this.systemName = systemName;
        return this;
    }

    public String getCodeName() {
        return codeName;
    }

    public PlatformCodeGenerator setCodeName(String codeName) {
        this.codeName = codeName;
        return this;
    }

    public String getServiceName() {
        return serviceName;
    }

    public PlatformCodeGenerator setServiceName(String serviceName) {
        this.serviceName = serviceName;
        return this;
    }

    public String getPackageName() {
        return packageName;
    }

    public PlatformCodeGenerator setPackageName(String packageName) {
        this.packageName = packageName;
        return this;
    }

    public String getPackageDir() {
        return packageDir;
    }

    public PlatformCodeGenerator setPackageDir(String packageDir) {
        this.packageDir = packageDir;
        return this;
    }

    public String getPackageWebDir() {
        return packageWebDir;
    }

    public PlatformCodeGenerator setPackageWebDir(String packageWebDir) {
        this.packageWebDir = packageWebDir;
        return this;
    }

    public String[] getTablePrefix() {
        return tablePrefix;
    }

    public PlatformCodeGenerator setTablePrefix(String[] tablePrefix) {
        this.tablePrefix = tablePrefix;
        return this;
    }

    public String[] getIncludeTables() {
        return includeTables;
    }

    public PlatformCodeGenerator setIncludeTables(String[] includeTables) {
        this.includeTables = includeTables;
        return this;
    }

    public String[] getExcludeTables() {
        return excludeTables;
    }

    public PlatformCodeGenerator setExcludeTables(String[] excludeTables) {
        this.excludeTables = excludeTables;
        return this;
    }

    public boolean isHasSuperEntity() {
        return hasSuperEntity;
    }

    public PlatformCodeGenerator setHasSuperEntity(boolean hasSuperEntity) {
        this.hasSuperEntity = hasSuperEntity;
        return this;
    }

    public boolean isHasWrapper() {
        return hasWrapper;
    }

    public PlatformCodeGenerator setHasWrapper(boolean hasWrapper) {
        this.hasWrapper = hasWrapper;
        return this;
    }

    public String[] getSuperEntityColumns() {
        return superEntityColumns;
    }

    public PlatformCodeGenerator setSuperEntityColumns(String[] superEntityColumns) {
        this.superEntityColumns = superEntityColumns;
        return this;
    }

    public String getTenantColumn() {
        return tenantColumn;
    }

    public PlatformCodeGenerator setTenantColumn(String tenantColumn) {
        this.tenantColumn = tenantColumn;
        return this;
    }

    public boolean isSwagger2() {
        return swagger2;
    }

    public PlatformCodeGenerator setSwagger2(boolean swagger2) {
        this.swagger2 = swagger2;
        return this;
    }

    public String getDriverName() {
        return driverName;
    }

    public PlatformCodeGenerator setDriverName(String driverName) {
        this.driverName = driverName;
        return this;
    }

    public String getUrl() {
        return url;
    }

    public PlatformCodeGenerator setUrl(String url) {
        this.url = url;
        return this;
    }

    public String getUsername() {
        return username;
    }

    public PlatformCodeGenerator setUsername(String username) {
        this.username = username;
        return this;
    }

    public String getPassword() {
        return password;
    }

    public PlatformCodeGenerator setPassword(String password) {
        this.password = password;
        return this;
    }

    public void run() {
        Properties props = getProperties();
        AutoGenerator mpg = new AutoGenerator();
        GlobalConfig gc = new GlobalConfig();
        String outputDir = getOutputDir();
        String author = props.getProperty("author");
        gc.setOutputDir(outputDir);
        gc.setAuthor(author);
        gc.setFileOverride(true);
        gc.setOpen(false);
        gc.setActiveRecord(false);
        gc.setEnableCache(false);
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("I%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        gc.setSwagger2(swagger2);
        mpg.setGlobalConfig(gc);
        DataSourceConfig dsc = new DataSourceConfig();
        DbType dataSourceDbType = this.dbType;
        if (null == dataSourceDbType) {
            dataSourceDbType = MyBatisPlusUtil.deduceDbTypeFromDriverName(() -> {
                String driverName = Func.toStr(this.driverName, props.getProperty(SystemPropertiesConstants.Spring.SPRING_DATASOURCE_DRIVER_CLASS_NAME));
                if (StrUtil.containsAny(driverName, DbType.MYSQL.getDb())) {
                    dsc.setDbType(DbType.MYSQL);
                    dsc.setTypeConvert(new MySqlTypeConvert());
                    return DbType.MYSQL;
                } else if (StrUtil.containsAny(driverName, DbType.POSTGRE_SQL.getDb())) {
                    dsc.setDbType(DbType.POSTGRE_SQL);
                    dsc.setTypeConvert(new PostgreSqlTypeConvert());
                    return DbType.POSTGRE_SQL;
                } else if (StrUtil.containsAny(driverName, DbType.SQL_SERVER.getDb())) {
                    dsc.setDbType(DbType.SQL_SERVER);
                    dsc.setTypeConvert(new SqlServerTypeConvert());
                    return DbType.SQL_SERVER;
                } else {
                    dsc.setDbType(DbType.ORACLE);
                    dsc.setTypeConvert(new OracleTypeConvert());
                    return DbType.ORACLE;
                }
            });
        }
//        //String driverName = Func.toStr(this.driverName, props.getProperty("spring.datasource.driver-class-name"));
//        String driverName = Func.toStr(this.driverName, props.getProperty(SystemPropertiesConstants.Spring.SPRING_DATASOURCE_DRIVER_CLASS_NAME));
//        if (StrUtil.containsAny(driverName, DbType.MYSQL.getDb())) {
//            dsc.setDbType(DbType.MYSQL);
//            dsc.setTypeConvert(new MySqlTypeConvert());
//        } else if (StrUtil.containsAny(driverName, DbType.POSTGRE_SQL.getDb())) {
//            dsc.setDbType(DbType.POSTGRE_SQL);
//            dsc.setTypeConvert(new PostgreSqlTypeConvert());
//        } else if (StrUtil.containsAny(driverName, DbType.SQL_SERVER.getDb())) {
//            dsc.setDbType(DbType.SQL_SERVER);
//            dsc.setTypeConvert(new SqlServerTypeConvert());
//        } else {
//            dsc.setDbType(DbType.ORACLE);
//            dsc.setTypeConvert(new OracleTypeConvert());
//        }
        dsc.setDriverName(driverName);
        /*
        dsc.setUrl(Func.toStr(this.url, props.getProperty("spring.datasource.url")));
        dsc.setUsername(Func.toStr(this.username, props.getProperty("spring.datasource.username")));
        dsc.setPassword(Func.toStr(this.password, props.getProperty("spring.datasource.password")));
        */
        dsc.setUrl(Func.toStr(this.url, props.getProperty(SystemPropertiesConstants.Spring.SPRING_DATASOURCE_URL)));
        dsc.setUsername(Func.toStr(this.username, props.getProperty(SystemPropertiesConstants.Spring.SPRING_DATASOURCE_USERNAME)));
        dsc.setPassword(Func.toStr(this.password, props.getProperty(SystemPropertiesConstants.Spring.SPRING_DATASOURCE_PASSWORD)));
        mpg.setDataSource(dsc);
        /*策略配置*/
        StrategyConfig strategy = new StrategyConfig();
        /*全局大写命名*/
        /*strategy.setCapitalMode(true);*/
        /*全局下划线命名*/
        /*strategy.setDbColumnUnderline(true);*/
//        strategy.setNaming(NamingStrategy.underline_to_camel);
//        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setNaming(null != myBatisPlusGeneratorConfigInfo ? ObjUtil.defaultIfNull(myBatisPlusGeneratorConfigInfo.getNaming(),
            NamingStrategy.underline_to_camel) : NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(null != myBatisPlusGeneratorConfigInfo ? ObjUtil.defaultIfNull(myBatisPlusGeneratorConfigInfo.getColumnNaming(),
            NamingStrategy.underline_to_camel): NamingStrategy.underline_to_camel);
        strategy.setTablePrefix(tablePrefix);
        if (includeTables.length > 0) {
            strategy.setInclude(includeTables);
        }
        if (excludeTables.length > 0) {
            strategy.setExclude(excludeTables);
        }
        if (hasSuperEntity) {
            strategy.setSuperEntityClass("org.zodiac.mybatisplus.base.BaseEntity");
            strategy.setSuperEntityColumns(superEntityColumns);
            strategy.setSuperServiceClass("org.zodiac.mybatisplus.base.BaseService");
            strategy.setSuperServiceImplClass("org.zodiac.mybatisplus.base.BaseServiceImpl");
        } else {
            strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService");
            strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");
        }
        /**/
        if (Springs.isServletWeb()) {
            strategy.setSuperControllerClass("org.zodiac.boot.ctrl.PlatformServletController");
        } else if (Springs.isReactiveWeb()) {
            strategy.setSuperControllerClass("org.zodiac.boot.ctrl.PlatformReactiveController");
        }
//        strategy.setEntityBuilderModel(false);
//        strategy.setChainModel(false);

//        strategy.setEntityLombokModel(true);
//        strategy.setControllerMappingHyphenStyle(true);
        strategy.setChainModel(null != myBatisPlusGeneratorConfigInfo ? myBatisPlusGeneratorConfigInfo.isChainModel() : false);
        strategy.setEntityLombokModel(null != myBatisPlusGeneratorConfigInfo ? myBatisPlusGeneratorConfigInfo.isEntityLombokModel() : true);
        strategy.setControllerMappingHyphenStyle(null != myBatisPlusGeneratorConfigInfo ? myBatisPlusGeneratorConfigInfo.isControllerMappingHyphenStyle() : true);
        mpg.setStrategy(strategy);
        /*包配置。*/
        PackageConfig pc = new PackageConfig();
        /*控制台扫描。*/
        pc.setModuleName(null);
        pc.setParent(packageName);
        pc.setController("controller");
        pc.setEntity("entity");
        pc.setXml("mapper");
        mpg.setPackageInfo(pc);
        mpg.setCfg(getInjectionConfig());
        mpg.execute();
    }

    private InjectionConfig getInjectionConfig() {
        String servicePackage = serviceName.split("-").length > 1 ? serviceName.split("-")[1] : serviceName;
        /*自定义配置。*/
        Map map = new HashMap<>(16);
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                map.put("codeName", codeName);
                map.put("serviceName", serviceName);
                map.put("servicePackage", servicePackage);
                map.put("servicePackageLowerCase", servicePackage.toLowerCase());
                map.put("tenantColumn", tenantColumn);
                map.put("hasWrapper", hasWrapper);
                this.setMap(map);
            }
        };
        List focList = new ArrayList<>();
        focList.add(new FileOutConfig("/META-INF/templates/sql/menu.sql.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                map.put("entityKey", (tableInfo.getEntityName().toLowerCase()));
                map.put("menuId", IdWorker.getId());
                map.put("addMenuId", IdWorker.getId());
                map.put("editMenuId", IdWorker.getId());
                map.put("removeMenuId", IdWorker.getId());
                map.put("viewMenuId", IdWorker.getId());
                return getOutputDir() + "/" + "/sql/" + tableInfo.getEntityName().toLowerCase() + ".menu.mysql";
            }
        });
        focList.add(new FileOutConfig("/META-INF/templates/entityVO.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return getOutputDir() + "/" + packageName.replace(".", "/") + "/" + "vo" + "/"
                    + tableInfo.getEntityName() + "VO" + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig("/META-INF/templates/entityDTO.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return getOutputDir() + "/" + packageName.replace(".", "/") + "/" + "dto" + "/"
                    + tableInfo.getEntityName() + "DTO" + StringPool.DOT_JAVA;
            }
        });
        if (hasWrapper) {
            focList.add(new FileOutConfig("/META-INF/templates/wrapper.java.vm") {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    return getOutputDir() + "/" + packageName.replace(".", "/") + "/" + "wrapper" + "/"
                        + tableInfo.getEntityName() + "Wrapper" + StringPool.DOT_JAVA;
                }
            });
        }
        if (Func.isNotBlank(packageWebDir)) {
            if (Func.equals(systemName, DevelopConstants.SWORD_NAME)) {
                focList.add(new FileOutConfig("/META-INF/templates/sword/action.js.vm") {
                    @Override
                    public String outputFile(TableInfo tableInfo) {
                        return getOutputWebDir() + "/actions" + "/" + tableInfo.getEntityName().toLowerCase() + MimeMappings.JS_FILE_SUFFIX;
                    }
                });
                focList.add(new FileOutConfig("/META-INF/templates/sword/model.js.vm") {
                    @Override
                    public String outputFile(TableInfo tableInfo) {
                        return getOutputWebDir() + "/models" + "/" + tableInfo.getEntityName().toLowerCase() + MimeMappings.JS_FILE_SUFFIX;
                    }
                });
                focList.add(new FileOutConfig("/META-INF/templates/sword/service.js.vm") {
                    @Override
                    public String outputFile(TableInfo tableInfo) {
                        return getOutputWebDir() + "/services" + "/" + tableInfo.getEntityName().toLowerCase() + MimeMappings.JS_FILE_SUFFIX;
                    }
                });
                focList.add(new FileOutConfig("/META-INF/templates/sword/list.js.vm") {
                    @Override
                    public String outputFile(TableInfo tableInfo) {
                        return getOutputWebDir() + "/pages" + "/" + StrUtil.upperCaseFirst(servicePackage) + "/"
                            + tableInfo.getEntityName() + "/" + tableInfo.getEntityName() + MimeMappings.JS_FILE_SUFFIX;
                    }
                });
                focList.add(new FileOutConfig("/META-INF/templates/sword/add.js.vm") {
                    @Override
                    public String outputFile(TableInfo tableInfo) {
                        return getOutputWebDir() + "/pages" + "/" + StrUtil.upperCaseFirst(servicePackage) + "/"
                            + tableInfo.getEntityName() + "/" + tableInfo.getEntityName() + "Add.js";
                    }
                });
                focList.add(new FileOutConfig("/META-INF/templates/sword/edit.js.vm") {
                    @Override
                    public String outputFile(TableInfo tableInfo) {
                        return getOutputWebDir() + "/pages" + "/" + StrUtil.upperCaseFirst(servicePackage) + "/"
                            + tableInfo.getEntityName() + "/" + tableInfo.getEntityName() + "Edit.js";
                    }
                });
                focList.add(new FileOutConfig("/META-INF/templates/sword/view.js.vm") {
                    @Override
                    public String outputFile(TableInfo tableInfo) {
                        return getOutputWebDir() + "/pages" + "/" + StrUtil.upperCaseFirst(servicePackage) + "/"
                            + tableInfo.getEntityName() + "/" + tableInfo.getEntityName() + "View.js";
                    }
                });
            } else if (Func.equals(systemName, DevelopConstants.SABER_NAME)) {
                focList.add(new FileOutConfig("/META-INF/templates/saber/api.js.vm") {
                    @Override
                    public String outputFile(TableInfo tableInfo) {
                        return getOutputWebDir() + "/api" + "/" + servicePackage.toLowerCase() + "/"
                            + tableInfo.getEntityName().toLowerCase() + MimeMappings.JS_FILE_SUFFIX;
                    }
                });
                focList.add(new FileOutConfig("/META-INF/templates/saber/crud.vue.vm") {
                    @Override
                    public String outputFile(TableInfo tableInfo) {
                        return getOutputWebDir() + "/views" + "/" + servicePackage.toLowerCase() + "/"
                            + tableInfo.getEntityName().toLowerCase() + ".vue";
                    }
                });
            }
        }
        cfg.setFileOutConfigList(focList);
        return cfg;
    }

    /**
     * 获取配置文件。
     *
     * @return 配置Props
     */
    private Properties getProperties() {
        /*读取配置文件*/
        Resource resource = new ClassPathResource("/META-INF/templates/code.properties");
        Properties props = new Properties();
        try {
            props = PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException e) {
            log.error("{}", ExceptionUtil.stackTrace(e));
        }
        return props;
    }

    /**
     * 生成到项目中。
     *
     * @return outputDir
     */
    public String getOutputDir() {
        return (Func.blank(packageDir) ? System.getProperty("user.dir") + "/platform-ops/platform-develop" : packageDir)
            + "/src/main/java";
    }

    /**
     * 生成到Web项目中。
     *
     * @return outputDir
     */
    public String getOutputWebDir() {
        return (Func.blank(packageWebDir) ? System.getProperty("user.dir") : packageWebDir) + "/src";
    }

    /**
     * 页面生成的文件名。
     * 
     * @param viewOutputDir 视图输出目录
     * @param tableInfo 表信息
     * @param suffixPath 后缀路径
     * @return 路径
     */
    private String getGeneratorViewPath(String viewOutputDir, TableInfo tableInfo, String suffixPath) {
        String name = StringUtils.firstToLowerCase(tableInfo.getEntityName());
        String path = viewOutputDir + "/" + name + "/" + name + suffixPath;
        File viewDir = new File(path).getParentFile();
        if (!viewDir.exists()) {
            viewDir.mkdirs();
        }
        return path;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy