天天看点

【springboot】便捷式代码生成器

【springboot】代码生成器v01

背景

  • 基于mybatis-puls生成的代码生成器,把配置化到配置文件中,方便开发人员方便配置. 方便集成lombok,swagger2

效果图

【springboot】便捷式代码生成器
【springboot】便捷式代码生成器

配置

创建一个基础工程
  • springboot 2.0 + gradle

build.gradle

/**
 * ===================================================================================================================
 * -------------------------------------------       引入项目插件         ----------------------------------------------
 * ===================================================================================================================
 */
plugins {
    id 'org.springframework.boot' version '2.2.6.RELEASE'           //spring提供的spring boot插件,主要用到了其依赖管理的功能.
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'    //spring jar版本管理
    id 'java'                                                       //java插件
    id 'maven-publish'                                              //该插件可以将打包的jar发送到maven库
}
/**
 * ===================================================================================================================
 * -------------------------------------------      所有项目的通用配置     ----------------------------------------------
 * ===================================================================================================================
 */
configure(allprojects) { project ->
    //项目基础属性
    group 'com.emodernhy'           //项目所属组织
    version '1.0-SNAPSHOT'          //项目版本号

    //引入插件
    apply plugin: 'java'                                            //java插件
    apply plugin: 'maven'                                           //maven插件
    apply plugin: 'idea'                                            //IDEA插件
    apply plugin: 'eclipse'                                         //eclipse插件
    apply plugin: 'org.springframework.boot'                        //spring boot插件
    apply plugin: 'io.spring.dependency-management'                 //实现maven的依赖统一管理功能
    apply from: "${rootProject.rootDir}/dependency.gradle"          //引入jar包版本配置文件

    //JDK版本声明
    sourceCompatibility = custom.version.JDK
    targetCompatibility = custom.version.JDK

    //配置仓库
    repositories {
        mavenLocal()
        maven { url 'http://maven.aliyun.com/nexus/content/groups/public' }
        maven { url 'https://repo.spring.io/libs-snapshot' }
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
        mavenCentral()
        jcenter()
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }

    //指定项目编码
    tasks.withType(JavaCompile) {
        options.encoding = "${custom.encoding.OPTIONS}"
    }

    //在多模块下,授权打包依赖模块
    jar {
        enabled = true
    }

    //重打包基础配置
    bootJar {
//        mainClassName = "jpanda.cloud.EurekaServer"
        launchScript()
        archiveName = "${project.group}_${project.name}_${project.version}.jar"
    }


}


/**
 * ===================================================================================================================
 * -------------------------------------------      所有所有项目的通用配置     ---------------------------------------------
 * ===================================================================================================================
 */
configure(allprojects) {
    project ->
        dependencyManagement {
            //定义版本
            dependencies {
                /**
                 * lombok
                 */
                dependency "org.projectlombok:lombok:${custom.version.LOMBOK}"
                /**
                 * hutool工具类
                 */
                dependency "cn.hutool:hutool-all:${custom.version.HUTOOL}"
                /**
                 * HikariCP数据库连接池
                 */
                dependency "com.zaxxer:HikariCP:${custom.version.HIKARI_CP}"
                /**
                 * mysql数据库驱动
                 */
                dependency "mysql:mysql-connector-java:${custom.version.MYSQL}"
                /**
                 * commons-lang3
                 */
                dependency "org.apache.commons:commons-lang3:${custom.version.APACHE_COMMON_LANG3}"
                /**
                 * MyBatis-Plus 的代码生成器
                 */
                dependency "com.baomidou:mybatis-plus-generator:${custom.version.MYBATIS_PLUS}"
            }
        }
}

configure(allprojects) {
    project ->
        /**
         * -============================================================================================================
         * -=====================================模块的公共依赖==================================================
         * -============================================================================================================
         */
        dependencies {
            /**
             * -=================================================================================-
             * - ********************       基本相关依赖      *************************** -
             * -=================================================================================-
             */
            //使用lombok来简化掉编码过程中的通用的方法.
            implementation 'org.projectlombok:lombok'
            //commons-lang3工具包
            implementation 'org.apache.commons:commons-lang3'
            //工具包
            implementation ('cn.hutool:hutool-all')
            /**
             * -=================================================================================-
             * - ********************       springboot相关jar      *************************** -
             * -=================================================================================-
             */
            implementation 'org.springframework.boot:spring-boot-starter'
            //web
            implementation 'org.springframework.boot:spring-boot-starter-web'
            //test
            testImplementation('org.springframework.boot:spring-boot-starter-test') {
                exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
            }
            //apo
            implementation 'org.springframework.boot:spring-boot-starter-aop'
            //yml,properties配置文件有提示
            implementation 'org.springframework.boot:spring-boot-configuration-processor'
            /**
             * -=================================================================================-
             * - ********************       数据库相关jar      *************************** -
             * -=================================================================================-
             */
            //MyBatis-Plus 的代码生成器
            implementation 'com.baomidou:mybatis-plus-generator'
            //velocity模板
            implementation 'org.apache.velocity:velocity-engine-core:2.2'
            //mysql数据库驱动
            implementation 'mysql:mysql-connector-java'
            //连接池
            implementation 'com.zaxxer:HikariCP'
            /**
             * -=================================================================================-
             * - ********************       其他相关jar      *************************** -
             * -=================================================================================-
             */
            //日志性能监控
            implementation 'org.perf4j:perf4j:0.9.16'
        }
}

           

代码

  • DataSourceConfigYaml.java
  • GlobalConfigYaml.java
  • PackageConfigYaml.java
  • StrategyConfigYaml.java
package com.emodernhy.generator.config.yaml;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.config.IDbQuery;
import com.baomidou.mybatisplus.generator.config.ITypeConvert;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * 代码生成器 数据源配置 yaml配置转实体
 *
 * @author bo.huang
 * @since 2020/4/21 9:59 下午
 */
@Configuration
@PropertySource(value = "classpath:application.yaml")
@ConfigurationProperties(prefix = "emodernhy.generator.datasource")
@Data
public class DataSourceConfigYaml {
    /**
     * 数据库信息查询
     */
    private IDbQuery dbQuery;
    /**
     * 数据库类型
     */
    private DbType dbType;
    /**
     * PostgreSQL schemaName
     */
    private String schemaName;
    /**
     * 类型转换
     */
    private ITypeConvert typeConvert;
    /**
     * 驱动连接的URL
     */
    private String url;
    /**
     * 驱动名称
     */
    private String driverName;
    /**
     * 数据库连接用户名
     */
    private String username;
    /**
     * 数据库连接密码
     */
    private String password;
}
           
package com.emodernhy.generator.config.yaml;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * 代码生成器 全局配置 yaml配置转实体
 *
 * @author bo.huang
 * @since 2020/4/21 9:19 下午
 */
@Configuration
@PropertySource(value = "classpath:application.yaml")
@ConfigurationProperties(prefix = "emodernhy.generator.global")
@Data
public class GlobalConfigYaml {
    /**
     * 生成文件的输出目录【默认 D 盘根目录】
     */
    private String outputDir = "D://";

    /**
     * 是否覆盖已有文件
     */
    private boolean fileOverride = true;

    /**
     * 是否打开输出目录
     */
    private boolean open = true;

    /**
     * 是否在xml中添加二级缓存配置
     */
    private boolean enableCache = false;

    /**
     * 开发人员
     */
    private String author;

    /**
     * 开启 Kotlin 模式
     */
    private boolean kotlin = false;

    /**
     * 开启 swagger2 模式
     */
    private boolean swagger2 = false;

    /**
     * 开启 ActiveRecord 模式
     */
    private boolean activeRecord = false;

    /**
     * 开启 BaseResultMap
     */
    private boolean baseResultMap = false;

    /**
     * 时间类型对应策略
     */
    private DateType dateType = DateType.TIME_PACK;

    /**
     * 开启 baseColumnList
     */
    private boolean baseColumnList = false;
    /**
     * 各层文件名称方式,例如: %sAction 生成 UserAction
     * %s 为占位符
     */
    private String entityName;
    private String mapperName;
    private String xmlName;
    private String serviceName;
    private String serviceImplName;
    private String controllerName;
    /**
     * 指定生成的主键的ID类型
     */
    private IdType idType;
}
           
package com.emodernhy.generator.config.yaml;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.Map;

/**
 * 代码生成器 包名配置 yaml配置转实体
 *
 * @author bo.huang
 * @since 2020/4/21 10:15 下午
 */
@Configuration
@PropertySource(value = "classpath:application.yaml")
@ConfigurationProperties(prefix = "emodernhy.generator.package")
@Data
public class PackageConfigYaml {
    /**
     * 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
     */
    private String parent = "com.baomidou";
    /**
     * 父包模块名
     */
    private String moduleName = null;
    /**
     * Entity包名
     */
    private String entity = "entity";
    /**
     * Service包名
     */
    private String service = "service";
    /**
     * Service Impl包名
     */
    private String serviceImpl = "service.impl";
    /**
     * Mapper包名
     */
    private String mapper = "mapper";
    /**
     * Mapper XML包名
     */
    private String xml = "mapper.xml";
    /**
     * Controller包名
     */
    private String controller = "controller";
    /**
     * 路径配置信息
     */
    private Map<String, String> pathInfo;
}
           
package com.emodernhy.generator.config.yaml;

import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.config.INameConvert;
import com.baomidou.mybatisplus.generator.config.po.LikeTable;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.List;

/**
 * 代码生成器 策略配置 yaml配置转实体
 *
 * @author bo.huang
 * @since 2020/4/21 10:13 下午
 */
@Configuration
@PropertySource(value = "classpath:application.yaml")
@ConfigurationProperties(prefix = "emodernhy.generator.strategy")
@Data
public class StrategyConfigYaml {
    /**
     * 是否大写命名
     */
    private boolean isCapitalMode = false;
    /**
     * 是否跳过视图
     */
    private boolean skipView = false;
    /**
     * 名称转换
     */
    private INameConvert nameConvert;
    /**
     * 数据库表映射到实体的命名策略
     */
    private NamingStrategy naming = NamingStrategy.no_change;
    /**
     * 数据库表字段映射到实体的命名策略
     * <p>未指定按照 naming 执行</p>
     */
    private NamingStrategy columnNaming = null;
    /**
     * 表前缀
     */
    private String[] tablePrefix;
    /**
     * 字段前缀
     */
    @Setter(AccessLevel.NONE)
    private String[] fieldPrefix;
    /**
     * 自定义继承的Entity类全称,带包名
     */
    @Setter(AccessLevel.NONE)
    private String superEntityClass;
    /**
     * 自定义基础的Entity类,公共字段
     */
    @Setter(AccessLevel.NONE)
    private String[] superEntityColumns;
    /**
     * 自定义继承的Mapper类全称,带包名
     */
    private String superMapperClass = ConstVal.SUPER_MAPPER_CLASS;
    /**
     * 自定义继承的Service类全称,带包名
     */
    private String superServiceClass = ConstVal.SUPER_SERVICE_CLASS;
    /**
     * 自定义继承的ServiceImpl类全称,带包名
     */
    private String superServiceImplClass = ConstVal.SUPER_SERVICE_IMPL_CLASS;
    /**
     * 自定义继承的Controller类全称,带包名
     */
    private String superControllerClass;
    /**
     * 需要包含的表名(与exclude二选一配置)
     * @since 3.3.0 正则匹配不再支持,请使用{@link #setLikeTable(LikeTable)}}
     */
    private String[] include = null;
    /**
     * 需要排除的表名
     * @since 3.3.0 正则匹配不再支持,请使用{@link #setNotLikeTable(LikeTable)}}
     */
    @Setter(AccessLevel.NONE)
    private String[] exclude = null;
    /**
     * 实体是否生成 serialVersionUID
     */
    private boolean entitySerialVersionUID = true;
    /**
     * 【实体】是否生成字段常量(默认 false)<br>
     * -----------------------------------<br>
     * public static final String ID = "test_id";
     */
    private boolean entityColumnConstant = false;
    /**
     * 【实体】是否为构建者模型(默认 false)<br>
     * -----------------------------------<br>
     * public User setName(String name) { this.name = name; return this; }
     */
    private boolean entityBuilderModel = false;
    /**
     * 【实体】是否为lombok模型(默认 false)<br>
     * <a href="https://projectlombok.org/" target="_blank" rel="external nofollow" >document</a>
     */
    private boolean entityLombokModel = false;
    /**
     * Boolean类型字段是否移除is前缀(默认 false)<br>
     * 比如 : 数据库字段名称 : 'is_xxx',类型为 : tinyint. 在映射实体的时候则会去掉is,在实体类中映射最终结果为 xxx
     */
    private boolean entityBooleanColumnRemoveIsPrefix = false;
    /**
     * 生成 <code>@RestController</code> 控制器
     * <pre>
     *      <code>@Controller</code> -> <code>@RestController</code>
     * </pre>
     */
    private boolean restControllerStyle = false;
    /**
     * 驼峰转连字符
     * <pre>
     *      <code>@RequestMapping("/managerUserActionHistory")</code> -> <code>@RequestMapping("/manager-user-action-history")</code>
     * </pre>
     */
    private boolean controllerMappingHyphenStyle = false;
    /**
     * 是否生成实体时,生成字段注解
     */
    private boolean entityTableFieldAnnotationEnable = false;
    /**
     * 乐观锁属性名称
     */
    private String versionFieldName;
    /**
     * 逻辑删除属性名称
     */
    private String logicDeleteFieldName;
    /**
     * 表填充字段
     */
    private List<TableFill> tableFillList = null;
    /**
     * 启用sql过滤
     * 语法不能支持使用sql过滤表的话,可以考虑关闭此开关.
     * 目前所知微软系需要关闭,其他数据库等待反馈,sql可能要改动一下才能支持,没数据库环境搞,请手动关闭使用内存过滤的方式。
     *
     * @since 3.3.1
     */
    private boolean enableSqlFilter = true;
    /**
     * 包含表名
     *
     * @since 3.3.0
     */
    private LikeTable likeTable;
    /**
     * 不包含表名
     *
     * @since 3.3.0
     */
    private LikeTable notLikeTable;
}
           
package com.emodernhy.generator.service;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.emodernhy.generator.config.yaml.DataSourceConfigYaml;
import com.emodernhy.generator.config.yaml.GlobalConfigYaml;
import com.emodernhy.generator.config.yaml.PackageConfigYaml;
import com.emodernhy.generator.config.yaml.StrategyConfigYaml;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * @author bo.huang
 * @since 2020/4/22 11:37 上午
 */
@Service
@Log
public class GeneratorService {

    /**
     * 全局配置
     */
    private final AutoGenerator autoGenerator;

    public GeneratorService(GlobalConfigYaml globalConfigYaml, DataSourceConfigYaml dataSourceConfigYaml,
                            StrategyConfigYaml strategyConfigYaml, PackageConfigYaml packageConfigYaml) {
        autoGenerator = new AutoGenerator();
        //全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        BeanUtils.copyProperties(globalConfigYaml, globalConfig);
        autoGenerator.setGlobalConfig(globalConfig);
        //数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        BeanUtils.copyProperties(dataSourceConfigYaml, dataSourceConfig);
        autoGenerator.setDataSource(dataSourceConfig);
        //策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        BeanUtils.copyProperties(strategyConfigYaml, strategyConfig);
        autoGenerator.setStrategy(strategyConfig);
        //包名配置
        PackageConfig packageConfig = new PackageConfig();
        BeanUtils.copyProperties(packageConfigYaml, packageConfig);
        autoGenerator.setPackageInfo(packageConfig);
    }

    /**
     * 生成后台代码
     *
     * @author bo.huang update
     * @date 2020/4/22 11:39 上午
     */
    public void start() {
        autoGenerator.execute();
    }
}
           

配置文件application.yaml

#=================代码生成器相关配置=================
emodernhy:
  generator:
    global:
      file-override: true
      open: false
      author: bo.huang
      swagger2: true
      date-type: only_date
      id-type: auto
      output-dir: D://mybatis
    datasource:
      db-type: mysql
      driver-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://xxx.xxx.xxx.xxx:3308/lagou?characterEncoding=utf8
      username: root
      password: xxxx
    strategy:
      entity-lombok-model: true
      table-prefix: "t_"
      naming: underline_to_camel
      rest-controller-style: true
    #      include: "t_demo"
    package:
      parent: "com.emonderhy.test"
      entity: "model"
           

最后执行 start()方法即可