mybatis-plus-generator使用mybatisPlus代码生成器生成代码、xmlsql拼接、自定义类

最近写了一个mybatisPlus代码生成器,用于生成sql拼接代码以及自定义类。
项目地址

!!!!使用前请先看README.md文件!!!!!!
!!!!使用前请先看README.md文件!!!!!!
!!!!使用前请先看README.md文件!!!!!!

代码有注释,先上代码。

pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lylbp</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis-plus-generator</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>

        <!-- oracle -->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>12.2.0.1</version>
        </dependency>

        <!--Mybatis Plus 代码生成-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!--Mybatis Plus 代码生成依赖-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.1</version>
        </dependency>

        <!--hutool工具类-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

生成器调用代码

package com.lylbp.generator.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.DbType;
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.VelocityTemplateEngine;
import com.lylbp.generator.config.Config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author weiwenbin
 */
public class GenneratorService {

    /**
     * 数据连接信息
     *
     * @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 GlobalConfig
     */
    private static GlobalConfig globalConfig() {
        return new GlobalConfig()
                //作者
                .setAuthor(Config.AUTHOR)
                //controller,service,mapper,serviceImpl输出路径
                .setOutputDir(Config.OUT_OUT_DIR)
                //是否覆盖已有文件
                .setFileOverride(Config.FILE_OVERRIDE)
                //是否打开输出目录
                .setOpen(false)
                //时间采用java 8,(操作工具类:JavaLib => DateTimeUtils)
                .setDateType(DateType.ONLY_DATE)
                //不需要ActiveRecord特性的请改为false
                .setActiveRecord(true)
                //XML 二级缓存
                .setEnableCache(false)
                //XML是否生成ResultMap
                .setBaseResultMap(true)
                //XML是否生成columList
                .setBaseColumnList(true)
                //XML enableCache
                .setEnableCache(false)
                //是否生成 kotlin 代码
                .setKotlin(false)
                //自定义文件命名,注意 %s 会自动填充表名
                .setEntityName(Config.FILE_NAME_ENTITY)
                .setMapperName(Config.FILE_NAME_MAPPER)
                .setXmlName(Config.FILE_NAME_XML)
                .setServiceName(Config.FILE_NAME_SERVICE)
                .setServiceImplName(Config.FILE_NAME_SERVICE_IMPL)
                .setControllerName(Config.FILE_NAME_CONTROLLER)
                //主键类型
                .setIdType(Config.ENTITY_ID_TYPE)
                //是否支持swagger2
                .setSwagger2(Config.SWAGGER_SUPPORT);
    }

    /**
     * 策略配置对象
     *
     * @param tablePrefixes 表前缀
     * @param tableNames    表前缀
     * @param fieldPrefixes 字段前缀
     * @return StrategyConfig
     */
    private static StrategyConfig strategyConfig(String[] tablePrefixes, String[] tableNames, String[] fieldPrefixes) {
        return new StrategyConfig()
                // 全局大写命名 ORACLE 注意
                .setCapitalMode(true)
                // 是否跳过视图
                .setSkipView(false)
                //.setDbColumnUnderline(true)
                // 此处可以修改为您的表前缀(数组)
                .setTablePrefix(tablePrefixes)
                // 字段前缀
                .setFieldPrefix(fieldPrefixes)
                // 表名生成策略
                .setNaming(NamingStrategy.underline_to_camel)
                //修改替换成你需要的表名,多个表名传数组
                .setInclude(tableNames)
                // 排除生成的表
                //.setExclude(new String[]{"test"})
                // entity是否支持lombok实体
                .setEntityLombokModel(Config.ENTITY_LOMBOK_SUPPORT)
                //entity是否为构建者模型
                .setChainModel(false)
                //entity是否生成字段常量(默认 false 可通过常量名获取数据库字段名  3.x支持lambda表达式
                .setEntityColumnConstant(false)
                // 逻辑删除属性名称
                .setLogicDeleteFieldName(Config.FIELD_LOGIC_DELETE_NAME)
                //是否为RestController
                .setRestControllerStyle(Config.IS_REST_CONTROLLER)
                //实体属性上添加表字段映射
                .setEntityTableFieldAnnotationEnable(true)
                ;
    }

    /**
     * 包配置对象
     *
     * @return PackageConfig
     */
    private static PackageConfig packageConfig() {
        return new PackageConfig()
                .setParent(null)
                .setController(ObjectUtil.isEmpty(Config.PACKAGE_NAME_CONTROLLER) ? null : Config.PACKAGE_NAME_CONTROLLER)
                .setEntity(ObjectUtil.isEmpty(Config.PACKAGE_NAME_ENTITY) ? null : Config.PACKAGE_NAME_ENTITY)
                .setMapper(ObjectUtil.isEmpty(Config.PACKAGE_NAME_MAPPER) ? null : Config.PACKAGE_NAME_MAPPER)
                .setService(ObjectUtil.isEmpty(Config.PACKAGE_NAME_SERVICE) ? null : Config.PACKAGE_NAME_SERVICE)
                .setServiceImpl(ObjectUtil.isEmpty(Config.PACKAGE_NAME_SERVICE_IMPL) ? null : Config.PACKAGE_NAME_SERVICE_IMPL)
                ;
    }

    /**
     * 自定义配置对象
     *
     * @param injectionConfig 表配置
     * @return InjectionConfig
     */
    private static InjectionConfig injectionConfig(InjectionConfig injectionConfig) {
        List<FileOutConfig> fileOutConfigList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(Config.XML_PATH) || ObjectUtil.isNotEmpty(Config.XML_TEMPLATE)) {
            // 自定义xml配置
            fileOutConfigList.add(new FileOutConfig(Config.XML_TEMPLATE) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    return Config.XML_PATH + "/" + tableInfo.getXmlName() + StringPool.DOT_XML;
                }
            });
        }

        if (ObjectUtil.isNotEmpty(Config.VO_TEMPLATE) || ObjectUtil.isNotEmpty(Config.VO_PATH)) {
            // 自定义输出VO配置
            fileOutConfigList.add(new FileOutConfig(Config.VO_TEMPLATE) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    return Config.VO_PATH + "/" + tableInfo.getEntityName() + "VO.java";
                }
            });
        }

        if (ObjectUtil.isNotEmpty(Config.QO_TEMPLATE) || ObjectUtil.isNotEmpty(Config.QO_PATH)) {
            // 自定义输出QO配置
            fileOutConfigList.add(new FileOutConfig(Config.QO_TEMPLATE) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    return Config.QO_PATH + "/" + tableInfo.getEntityName() + "QO.java";
                }
            });
        }

        if (ObjectUtil.isNotEmpty(Config.DTO_TEMPLATE) || ObjectUtil.isNotEmpty(Config.DTO_PATH)) {
            // 自定义输出DTO配置
            fileOutConfigList.add(new FileOutConfig(Config.DTO_TEMPLATE) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    return Config.DTO_PATH + "/" + tableInfo.getEntityName() + "DTO.java";
                }
            });
        }


        injectionConfig.setFileOutConfigList(fileOutConfigList);

        return injectionConfig;
    }

    /**
     * 执行
     *
     * @param dbType        数据库类型
     * @param dbUrl         数据库地址
     * @param username      数据库用户名
     * @param password      数据库密码
     * @param driver        数据库驱动
     * @param tablePrefixes 表前缀
     * @param tableNames    表明
     * @param fieldPrefixes 字段前缀
     */
    public static void execute(DbType dbType, String dbUrl, String username, String password, String driver,
                               String[] tablePrefixes, String[] tableNames, String[] fieldPrefixes) {
        //要生成的表数组为空直接中断
        if (ArrayUtil.isAllEmpty(tableNames)) {
            return;
        }

        //mabatis-plus全局配置
        GlobalConfig globalConfig = globalConfig();

        //数据库配置对象
        DataSourceConfig dataSourceConfig = dataSourceConfig(dbType, dbUrl, username, password, driver);

        // 策略配置
        StrategyConfig strategyConfig = strategyConfig(tablePrefixes, tableNames, fieldPrefixes);
        // 策略配置--controller父类
        if (ObjectUtil.isNotEmpty(Config.SUPER_CONTROLLER_CLASS)) {
            strategyConfig.setSuperControllerClass(Config.SUPER_CONTROLLER_CLASS);
        }

        //包信息配置
        PackageConfig packageConfig = packageConfig();

        // 自定义配置
        InjectionConfig injectionConfig = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>(10);
                map.put("VOPackage", Config.PACKAGE_NAME_VO);
                map.put("QOPackage", Config.PACKAGE_NAME_QO);
                map.put("DTOPackage", Config.PACKAGE_NAME_DTO);
                map.put("DBType", dbType.getDb());
                map.put("FieldlogicDeleteName", Config.FIELD_LOGIC_DELETE_NAME);
                this.setMap(map);
            }
        };
        injectionConfig = injectionConfig(injectionConfig);

        //设置模版
        TemplateConfig tc = new TemplateConfig();
        tc.setMapper(Config.MAPPER_TEMPLATE);
        tc.setService(Config.SERVICE_TEMPLATE);
        tc.setServiceImpl(Config.SERVICE_IMPL_TEMPLATE);
        tc.setController(Config.CONTROLLER_TEMPLATE);
        //已自定义xml模版以及输出路径顾这里写null,不然默认会在mapper目录下生成一个xml
        tc.setXml(null);

        //代码生成
        new AutoGenerator()
                .setGlobalConfig(globalConfig)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageConfig)
                .setCfg(injectionConfig)
                .setTemplateEngine(new VelocityTemplateEngine())
                .setTemplate(tc)
                .execute();
    }

}

生成的代码

以mysql表中area为例,表结构如下

在这里插入图片描述

生成的xml代码如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dar.app.biz.dispatch.mapper.AreaMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.dar.app.biz.dispatch.entity.Area">
        <id column="area_id" property="areaId"/>
        <!-- 父级id -->
        <result column="pid" property="pid"/>
        <!-- 是否有效 -->
        <result column="is_valid" property="isValid"/>
        <!-- 名称 -->
        <result column="name" property="name"/>
        <!-- 创建时间 -->
        <result column="create_time" property="createTime"/>
        <!-- 创建日期 -->
        <result column="create_date" property="createDate"/>
    </resultMap>


    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
            t.area_id,
            t.pid,
            t.is_valid,
            t.name,
            t.create_time,
            t.create_date
        </sql>

    <!-- 通用查询语句(数据库comment中含有?则不显示字段注释)) -->
    <sql id="Base_Where_List">

        <if test="params.containsKey('areaId')">
            AND t.area_id = #{params.areaId}
        </if>


        <!-- 父级id查询 -->
        <if test="params.pid != null and params.pid != ''">
            AND t.pid = #{params.pid}
        </if>

        <!-- 父级id模糊查询 -->
        <if test="params.pidLike != null and params.pidLike != ''">
            AND t.pid LIKE CONCAT('%', #{params.pidLike}, '%')
        </if>


        <!-- 是否有效查询 -->
        <if test="params.isValid != null and params.isValid != ''">
            AND t.is_valid = #{params.isValid}
        </if>


        <!-- 名称查询 -->
        <if test="params.name != null and params.name != ''">
            AND t.name = #{params.name}
        </if>

        <!-- 名称模糊查询 -->
        <if test="params.nameLike != null and params.nameLike != ''">
            AND t.name LIKE CONCAT('%', #{params.nameLike}, '%')
        </if>


        <!-- 创建时间开始时间查询 -->
        <if test="params.createTimeStart != null and params.createTimeStart != ''">
            AND t.create_time &gt;= to_date(#{params.createTimeStart}, 'yyyy-mm-dd HH24:MI:SS')
        </if>

        <!-- 创建时间结束时间查询 -->
        <if test="params.createTimeEnd != null and params.createTimeEnd != ''">
            AND t.create_time &lt;= to_date(#{params.createTimeEnd}, 'yyyy-mm-dd HH24:MI:SS')
        </if>


        <!-- 创建日期开始时间查询 -->
        <if test="params.createDateStart != null and params.createDateStart != ''">
            AND t.create_date &gt;= to_date(#{params.createDateStart}, 'yyyy-mm-dd HH24:MI:SS')
        </if>

        <!-- 创建日期结束时间查询 -->
        <if test="params.createDateEnd != null and params.createDateEnd != ''">
            AND t.create_date &lt;= to_date(#{params.createDateEnd}, 'yyyy-mm-dd HH24:MI:SS')
        </if>
    </sql>

    <!-- AreaVO查询语句 -->
    <select id="queryAreaVOByParams" parameterType="java.util.Map" resultType="com.dar.app.biz.dispatch.vo.AreaVO">
        SELECT
        <include refid="Base_Column_List"/>
        FROM area t
        <where>
            <include refid="Base_Where_List"/>
        </where>
    </select>
</mapper>

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值