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

matrix.boot.jdbc.orm.mybatis.utils.GenerateMybatisCodeUtil Maven / Gradle / Ivy

package matrix.boot.jdbc.orm.mybatis.utils;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
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.FreemarkerTemplateEngine;
import matrix.boot.common.utils.StringUtil;
import matrix.boot.jdbc.orm.mybatis.dto.GenerateDto;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.*;

/**
 * 生成mybatis代码工具
 *
 * @author wangcheng
 * 2021/8/19
 **/
public class GenerateMybatisCodeUtil {

    /**
     * mapper 包名
     */
    private static final String MAPPER_NAME = "mapper";

    /**
     * service 包名
     */
    private static final String SERVICE_NAME = "service";

    /**
     * 实体 包名
     */
    private static final String ENTITY_NAME = "entity";

    /**
     * 项目路径
     */
    public static String PROJECT_PATH = System.getProperty("user.dir");

    /**
     * class路径
     */
    public static final String SRC_MAIN_JAVA = "src/main/java";

    /**
     * resource路径
     */
    public static final String SRC_MAIN_RESOURCE = "src/main/resources";

    /**
     * 作者
     */
    public static final String AUTHOR = System.getProperty("user.name");

    /**
     * 生成文件
     *
     * @param params     生成参数
     * @param tableNames 表名
     */
    public static void generate(GenerateDto params, String... tableNames) {
        FastAutoGenerator.create(params.getUrl(), params.getUsername(), params.getPassword())
                //全局配置
                .globalConfig(builder -> {
                    builder.disableOpenDir()
                            .outputDir(PROJECT_PATH + File.separator + params.getModuleName() + File.separator + SRC_MAIN_JAVA)
                            .author(AUTHOR)
                            .commentDate("yyyy-MM-dd")
                            .dateType(DateType.ONLY_DATE);
                    if (params.isEnableSwagger()) {
                        builder.enableSwagger();
                    }
                })
                //包配置
                .packageConfig(builder -> builder.parent(params.getPackageName())
                        .entity(ENTITY_NAME)
                        .mapper(MAPPER_NAME)
                        .service(SERVICE_NAME)
                        .serviceImpl(SERVICE_NAME + StringPool.DOT + "impl")
                        .other(StringUtils.EMPTY)
                        .pathInfo(Collections.singletonMap(OutputFile.xml, PROJECT_PATH + File.separator + params.getModuleName() + File.separator + SRC_MAIN_RESOURCE + File.separator + MAPPER_NAME))
                )
                //模板配置
                .templateConfig(builder -> builder.entity("/templates/mybatis/entity.java")
                        .mapper("/templates/mybatis/mapper.java")
                        .xml("/templates/mybatis/mapper.xml")
                        .service("/templates/mybatis/service.java")
                        .serviceImpl("/templates/mybatis/serviceImpl.java")
                        .controller("/templates/mybatis/controller.java"))
                //策略配置
                .strategyConfig(builder -> builder.enableCapitalMode()
                        .addInclude(tableNames)
                        .addTablePrefix(params.getTablePrefix())
                        .enableSkipView()
                        .entityBuilder()
                        .enableLombok()
                        .enableChainModel()
                        .superClass(params.getBaseEntityClass() != null ? params.getBaseEntityClass().getName() : StringUtils.EMPTY)
                        .formatFileName("%sEntity")
                        .idType(IdType.ASSIGN_ID)
                        .naming(NamingStrategy.underline_to_camel)
                        .enableTableFieldAnnotation()
                        .serviceBuilder().formatServiceFileName("%sService")
                        .controllerBuilder().enableRestStyle().enableHyphenStyle()
                        .mapperBuilder().enableMapperAnnotation())
                //注入配置
                .injectionConfig(consumer -> {
                    Map customFile = new HashMap<>();
                    customFile.put("Dto.java", "/templates/mybatis/dto.java.ftl");
                    customFile.put("QueryVo.java", "/templates/mybatis/queryVo.java.ftl");
                    customFile.put("SaveVo.java", "/templates/mybatis/saveVo.java.ftl");
                    consumer.customFile(customFile);
                })
                //模板配置
                .templateEngine(new EnhanceFreemarkerTemplateEngine(params))
                .execute();
    }

    /**
     * 自定义模板引擎
     */
    public static final class EnhanceFreemarkerTemplateEngine extends FreemarkerTemplateEngine {

        /**
         * 参数信息
         */
        private final GenerateDto params;

        public EnhanceFreemarkerTemplateEngine(GenerateDto params) {
            this.params = params;
        }

        @Override
        protected void outputCustomFile(Map customFile, TableInfo tableInfo, Map objectMap) {
            String entityName = tableInfo.getEntityName();
            //controller 映射短语
            String controllerMappingHyphen = (String) objectMap.get("controllerMappingHyphen");
            objectMap.put("controllerMappingHyphen", controllerMappingHyphen.substring(0, controllerMappingHyphen.lastIndexOf("-entity")));
            //组装实体短名称
            String name = entityName.substring(0, entityName.lastIndexOf("Entity"));
            objectMap.put("javaName", name);
            //组装变量端名称
            objectMap.put("varName", name.substring(0, 1).toLowerCase() + name.substring(1));
            //组装vo和dto 字段的pkg导入包
            Set fieldImportPackages = new LinkedHashSet<>();
            tableInfo.getFields().forEach(tableField -> {
                if (!StringUtil.isEmpty(tableField.getColumnType().getPkg())) {
                    fieldImportPackages.add(tableField.getColumnType().getPkg());
                }
            });
            objectMap.put("fieldImportPackages", fieldImportPackages);
            //放入主键是否要转String
            objectMap.put("enableKeyToString", params.isEnableKeyToString());
            if (!StringUtil.isEmpty(params.getKeySuffix())) {
                //放入主键是否要转String的keySuffix
                objectMap.put("keySuffix", params.getKeySuffix());
            }
            String otherPath = this.getPathInfo(OutputFile.other);
            customFile.forEach((key, value) -> {
                String fileName = "";
                if (key.contains("Dto.java")) {
                    fileName = String.format(otherPath + File.separator + "dto" + File.separator + name + "%s", key);
                } else if (key.contains("Vo.java")) {
                    fileName = String.format(otherPath + File.separator + "vo" + File.separator + name + "%s", key);
                }
                this.outputFile(new File(fileName), objectMap, value, Objects.requireNonNull(this.getConfigBuilder().getInjectionConfig()).isFileOverride());
            });
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy