美文网首页
mybatis-plus代码生成

mybatis-plus代码生成

作者: small瓜瓜 | 来源:发表于2019-08-10 22:38 被阅读0次
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine;
import com.sun.javafx.scene.shape.PathUtils;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;

import java.io.File;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class CodeGenerator {

    public static void main(String[] args) {

        /*
            全局配置
        */
        String projectPath = System.getProperty("user.dir");
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(projectPath + "/src/main/java") // 生成路径
                .setAuthor("zjb")                     // 设置作者
                .setOpen(false)                         // 文件生成完成后是否用打开相应的生成路径
                .setFileOverride(true)                  // 是否覆盖已有文件
                .setIdType(IdType.ID_WORKER)                 // 主键策略
                .setEnableCache(true)                   // 是否开启二级缓存,默认false
                .setKotlin(false)                       // 开启 Kotlin 模式,默认false
                .setSwagger2(false)                     // 开启 swagger2 模式,默认false
//                .setActiveRecord(false)                 // 开启 ActiveRecord 模式
//                .setActiveRecord(true)                // AR模式,就是bean有增删改查方法,继承自Model类
                .setDateType(DateType.ONLY_DATE)        // 时间类型对应策略
//                .setDateType()
                .setEntityName("%sBean")              // 实体命名方式
                .setMapperName("%sMapper")              // mapper 命名方式
                .setXmlName("%sMapper")              // Mapper xml 命名方式
                .setServiceName("%sService")           // 设置生成的service接口的名字的首字母是否为I
                .setServiceImplName("%sServiceImp")                   //service impl 命名方式
                .setControllerName("%sController")
                .setBaseResultMap(true)                 // 是否要有映射ResultMap
                .setBaseColumnList(true);               // 是否要有基础的列

        /*

        数据源配置

        */
        MySqlQuery mySqlQuery = new MySqlQuery() {
            @Override
            public String[] fieldCustom() {
                return new String[]{"Default"};
            }
        };

//        String[] strings = mySqlQuery.fieldCustom();

        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8&useUnicode=true&useSSL=false&characterEncoding=utf8")
                .setDbType(DbType.MYSQL)     //设置数据库类型[必须属性]
                .setDriverName("com.mysql.cj.jdbc.Driver")
                .setDbQuery(mySqlQuery)  //
                .setUsername("root")
//                .setTypeConvert((globalConfig, fieldType) -> null) // 自定义映射属性
                .setPassword("");


        /*

        策略配置 数据表配置

        */
        StrategyConfig strategy = new StrategyConfig();
        strategy.setCapitalMode(true)           //全局大写命名
                .setSkipView(true)              // 是否跳过视图
                .setLogicDeleteFieldName("deleted") // 添加逻辑删除列
//                .setVersionFieldName("version1")    // 添加版本号充当乐观锁
                .setEntitySerialVersionUID(false)   //  实体是否生成 serialVersionUID,默认为true
                .setControllerMappingHyphenStyle(true) //驼峰转连字符,比如:/userEntity -> /user-entity
                .setEntityBuilderModel(true)               // 点进去有介绍
                .setEntityColumnConstant(true)          // 点进去有介绍
//                NamingStrategy.no_change
                .setNaming(NamingStrategy.underline_to_camel)   // 数据库表映射到实例命名,下划线到驼峰
                .setNameConvert(new INameConvert() {

                    @Override
                    public String entityNameConvert(TableInfo tableInfo) {
                        System.out.println(tableInfo.getName());
                        return tableInfo.getName();
                    }

                    @Override
                    public String propertyNameConvert(TableField field) {
                        System.out.println(field.getName());
                        return field.getName();
                    }
                }) // 名称转换接口
                .setColumnNaming(NamingStrategy.underline_to_camel)  // 数据库表中的字段映射到实例命名,下划线到驼峰
//                .setTablePrefix("kk")                 // 设置要生成代码的数据表前缀
//                .setFieldPrefix("kk")                 // 设置要生成代码的数据表中字段前缀
                .setInclude("wt_.+")                     // 设置要包含的表
//                .setTableFillList(Arrays.asList(new TableFill("id", FieldFill.INSERT))) //属性填充
//                .setColumnNaming()
//                .setExclude()                         // 与包含二选一,排除那些表,两个都允许正则表达式
//                .setSuperEntityClass() //设置实体类要继承的超类
//                .setSuperEntityColumns()      // 自定义基础的Entity类,公共字段
//                .setSuperMapperClass()        //  自定义继承的Mapper类全称,带包名
                .setEntityLombokModel(true) // 设置生成的实体类是Lombok模式
                .setRestControllerStyle(true);  //


        /*

        包配置

        */
        PackageConfig pc = new PackageConfig();

//        pathInfo = new HashMap<>(6);
//        setPathInfo(pathInfo, template.getEntity(getGlobalConfig().isKotlin()), outputDir, ConstVal.ENTITY_PATH, ConstVal.ENTITY);
//        setPathInfo(pathInfo, template.getMapper(), outputDir, ConstVal.MAPPER_PATH, ConstVal.MAPPER);
//        setPathInfo(pathInfo, template.getXml(), outputDir, ConstVal.XML_PATH, ConstVal.XML);
//        setPathInfo(pathInfo, template.getService(), outputDir, ConstVal.SERVICE_PATH, ConstVal.SERVICE);
//        setPathInfo(pathInfo, template.getServiceImpl(), outputDir, ConstVal.SERVICE_IMPL_PATH, ConstVal.SERVICE_IMPL);
//        setPathInfo(pathInfo, template.getController(), outputDir, ConstVal.CONTROLLER_PATH, ConstVal.CONTROLLER);

        pc.setParent("top.itreatment")    // 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
                .setMapper("mapper")      // 设置mapper输出的位置
                .setXml("mapper.xml")     // 设置mapper对应的xml输出的位置
//                .setModuleName("bc")      // 父设置模块名
//                .setPathInfo()           // 路径配置信息,就是配置各个文件模板的路径信息
                .setService("service")    // 设置service输出的位置
                .setController("controller") // 设置controller输出的位置
                .setServiceImpl("service.impl") // 设置serviceImpl输出的位置
                .setModuleName("bc")
                .setEntity("beans");        // 设置beans输出的位置

      /*
          自定义配置,少了这一步会出现空指针异常,在下面这个方法的返回时,出现空指针
           com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine.getObjectMap
      */
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
                map.put("name", "zjb");
                map.put("age", 24);
                map.put("sex", "男");
                setMap(map);
            }
        };

//        cfg.setFileOutConfigList(Collections.singletonList(new FileOutConfig("entity.java.btl") {
//
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                return System.getProperty("user.home") + File.separator + "desktop" + File.separator + "123.txt";
//            }
//        }));
//        cfg.setFileCreate()       自定义判断是否创建文件


         /*

            代码生成器,将前面的初始化工作进行处理

         */
        AutoGenerator mpg = new AutoGenerator();
//        全局配置
        mpg.setGlobalConfig(gc);
//        数据源配置
        mpg.setDataSource(dsc);
//        策略配置
        mpg.setStrategy(strategy);
//        包配置
        mpg.setPackageInfo(pc);
//        自定义配置
        mpg.setCfg(cfg);
//        设置使用Beetl模板引擎
        BeetlTemplateEngine beetlTemplateEngine = new BeetlTemplateEngine();
        mpg.setTemplateEngine(beetlTemplateEngine);
//        执行
        mpg.execute();
    }
}
/*
 * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.baomidou.mybatisplus.generator.config;

import com.baomidou.mybatisplus.core.toolkit.StringPool;

import java.nio.charset.StandardCharsets;

/**
 * 定义常量
 *
 * @author YangHu, tangguo, hubin
 * @since 2016-08-31
 */
public interface ConstVal {

    String MODULE_NAME = "ModuleName";

    String ENTITY = "Entity";
    String SERVICE = "Service";
    String SERVICE_IMPL = "ServiceImpl";
    String MAPPER = "Mapper";
    String XML = "Xml";
    String CONTROLLER = "Controller";

    String ENTITY_PATH = "entity_path";
    String SERVICE_PATH = "service_path";
    String SERVICE_IMPL_PATH = "service_impl_path";
    String MAPPER_PATH = "mapper_path";
    String XML_PATH = "xml_path";
    String CONTROLLER_PATH = "controller_path";

    String JAVA_TMPDIR = "java.io.tmpdir";
    String UTF8 = StandardCharsets.UTF_8.name();
    String UNDERLINE = "_";

    String JAVA_SUFFIX = StringPool.DOT_JAVA;
    String KT_SUFFIX = ".kt";
    String XML_SUFFIX = ".xml";

    String TEMPLATE_ENTITY_JAVA = "/templates/entity.java";
    String TEMPLATE_ENTITY_KT = "/templates/entity.kt";
    String TEMPLATE_MAPPER = "/templates/mapper.java";
    String TEMPLATE_XML = "/templates/mapper.xml";
    String TEMPLATE_SERVICE = "/templates/service.java";
    String TEMPLATE_SERVICE_IMPL = "/templates/serviceImpl.java";
    String TEMPLATE_CONTROLLER = "/templates/controller.java";

    String VM_LOAD_PATH_KEY = "file.resource.loader.class";
    String VM_LOAD_PATH_VALUE = "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader";

    String SUPER_MAPPER_CLASS = "com.baomidou.mybatisplus.core.mapper.BaseMapper";
    String SUPER_SERVICE_CLASS = "com.baomidou.mybatisplus.extension.service.IService";
    String SUPER_SERVICE_IMPL_CLASS = "com.baomidou.mybatisplus.extension.service.impl.ServiceImpl";
}
public Map<String, Object> getObjectMap(TableInfo tableInfo) {
        Map<String, Object> objectMap = new HashMap<>(30);
        ConfigBuilder config = getConfigBuilder();
        if (config.getStrategyConfig().isControllerMappingHyphenStyle()) {
            objectMap.put("controllerMappingHyphenStyle", config.getStrategyConfig().isControllerMappingHyphenStyle());
            objectMap.put("controllerMappingHyphen", StringUtils.camelToHyphen(tableInfo.getEntityPath()));
        }
        objectMap.put("restControllerStyle", config.getStrategyConfig().isRestControllerStyle());
        objectMap.put("config", config);
        objectMap.put("package", config.getPackageInfo());
        GlobalConfig globalConfig = config.getGlobalConfig();
        objectMap.put("author", globalConfig.getAuthor());
        objectMap.put("idType", globalConfig.getIdType() == null ? null : globalConfig.getIdType().toString());
        objectMap.put("logicDeleteFieldName", config.getStrategyConfig().getLogicDeleteFieldName());
        objectMap.put("versionFieldName", config.getStrategyConfig().getVersionFieldName());
        objectMap.put("activeRecord", globalConfig.isActiveRecord());
        objectMap.put("kotlin", globalConfig.isKotlin());
        objectMap.put("swagger2", globalConfig.isSwagger2());
        objectMap.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        objectMap.put("table", tableInfo);
        objectMap.put("enableCache", globalConfig.isEnableCache());
        objectMap.put("baseResultMap", globalConfig.isBaseResultMap());
        objectMap.put("baseColumnList", globalConfig.isBaseColumnList());
        objectMap.put("entity", tableInfo.getEntityName());
        objectMap.put("entitySerialVersionUID", config.getStrategyConfig().isEntitySerialVersionUID());
        objectMap.put("entityColumnConstant", config.getStrategyConfig().isEntityColumnConstant());
        objectMap.put("entityBuilderModel", config.getStrategyConfig().isEntityBuilderModel());
        objectMap.put("entityLombokModel", config.getStrategyConfig().isEntityLombokModel());
        objectMap.put("entityBooleanColumnRemoveIsPrefix", config.getStrategyConfig().isEntityBooleanColumnRemoveIsPrefix());
        objectMap.put("superEntityClass", getSuperClassName(config.getSuperEntityClass()));
        objectMap.put("superMapperClassPackage", config.getSuperMapperClass());
        objectMap.put("superMapperClass", getSuperClassName(config.getSuperMapperClass()));
        objectMap.put("superServiceClassPackage", config.getSuperServiceClass());
        objectMap.put("superServiceClass", getSuperClassName(config.getSuperServiceClass()));
        objectMap.put("superServiceImplClassPackage", config.getSuperServiceImplClass());
        objectMap.put("superServiceImplClass", getSuperClassName(config.getSuperServiceImplClass()));
        objectMap.put("superControllerClassPackage", config.getSuperControllerClass());
        objectMap.put("superControllerClass", getSuperClassName(config.getSuperControllerClass()));
        return config.getInjectionConfig().prepareObjectMap(objectMap);
    }

相关文章

网友评论

      本文标题:mybatis-plus代码生成

      本文链接:https://www.haomeiwen.com/subject/cdkrjctx.html