SpringBoot集成MyBatis-Plus代碼生成器

1. 想詳細(xì)了解MyBatis-Plus代碼生成器可以先去官網(wǎng)了解

image.png

2. 集成

先新建spring boot工程mp-generator ,并添加依賴(如果是聚合項(xiàng)目场靴,可以新建模塊集成)

<!--  spring web依賴  -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
</dependency>

<!--  mysql和mybatis-plus依賴  -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.0</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.0</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version>
</dependency>

<!--  工具依賴  -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
</dependency>

3. 添加配置

新建entity包怀伦,添加一個(gè)實(shí)體類的父類

package com.mp.generator.entity;

import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;

@Data
public abstract class BaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "主鍵")
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @ApiModelProperty(value = "是否刪除瓮床,0 未刪除, 1 刪除")
    @TableLogic
    @TableField(value = "deleted", fill = FieldFill.INSERT)
    private Integer deleted;

    @ApiModelProperty(value = "是否可用难礼,1 可用挣郭,0 不可用")
    @TableField(value = "available", fill = FieldFill.INSERT)
    private Integer available;

    @ApiModelProperty(value = "創(chuàng)建時(shí)間")
    @TableField(value = "create_time", fill = FieldFill.INSERT)
    private Date createTime;

    @ApiModelProperty(value = "修改時(shí)間")
    @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;

}

新建config包,在包下添加Config類蟀架,配置全局信息

package com.mp.generator.config;

public class Config {

    public static String URL = "jdbc:mysql://127.0.0.1:3306/dynamic1?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true";
    public static String USERNAME = "root";
    public static String PASSWORD = "123456";
    public static String DRIVER = "com.mysql.cj.jdbc.Driver";

    /**
     * 包名
     */
    public static final String PACKAGE_PARENT = "com.mp.generator";
    public static final String PACKAGE_NAME_CONTROLLER = "controller";
    public static final String PACKAGE_NAME_MODEL = "entity";
    public static final String PACKAGE_NAME_DAO = "mapper";
    public static final String PACKAGE_NAME_SERVICE = "service";
    public static final String PACKAGE_NAME_SERVICE_IMPL = "service.impl";

    /**
     * 文件名后綴:Dao
     */
    public static final String FILE_NAME_DAO = "%sMapper";

    /**
     * 文件名后綴:MapperXml
     */
    public static final String FILE_NAME_XML = "%sMapper";

    /**
     * MP開頭,Service結(jié)尾
     */
    public static final String FILE_NAME_SERVICE = "%sService";

    /**
     * 文件名后綴:ServiceImpl
     */
    public static final String FILE_NAME_SERVICE_IMPL = "%sServiceImpl";

    /**
     * 文件名后綴:Controller
     */
    public static final String FILE_NAME_CONTROLLER = "%sController";

    /**
     * 邏輯刪除字段
     */
    public static final String FIELD_LOGIC_DELETE_NAME = "deleted";

    /**
     * 作者
     */
    public static final String AUTHOR = "generator";

    /**
     * 生成文件的輸出目錄
     */
//    public static String projectPath = System.getProperty("user.dir") + "/mp-generator";
    public static String projectPath = System.getProperty("user.dir");

    /**
     * 輸出目錄
     */
    public static final String outputDir = projectPath + "/src/main/java";

    /**
     * 模板引擎榆骚。velocity / freemarker / beetl
     */
    public static final String TEMPLATE_ENGINE = "freemarker";

    /**
     * 是否支持Swagger片拍,默認(rèn)不支持
     */
    public static final Boolean SWAGGER_SUPPORT = true;

}

新建utils包,添加CommonUtils類妓肢,配置生成信息

package com.mp.generator.utils;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
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.AbstractTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import com.mp.generator.config.Config;

import com.mp.generator.entity.BaseEntity;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CommonUtils {

    //讀取控制臺(tái)內(nèi)容
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("請(qǐng)輸入" + tip + ":");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("請(qǐng)輸入正確的" + tip + "捌省!");
    }

    //數(shù)據(jù)連接信息
    private static DataSourceConfig dataSourceConfig() {
        return new DataSourceConfig()
                .setDbType(DbType.MYSQL)
                .setUrl(Config.URL)
                .setUsername(Config.USERNAME)
                .setPassword(Config.PASSWORD)
                .setDriverName(Config.DRIVER)
                ;
    }

    // 配置
    private static GlobalConfig globalConfig() {
        return new GlobalConfig()
                .setAuthor(scanner("作者"))
                .setOutputDir(Config.outputDir)
                .setFileOverride(true) // 是否覆蓋已有文件
                .setOpen(false) // 是否打開輸出目錄
                .setDateType(DateType.ONLY_DATE) // 時(shí)間采用java 8,(操作工具類:JavaLib => DateTimeUtils)
                .setEnableCache(false)// XML 二級(jí)緩存
                .setBaseResultMap(false)// XML ResultMap
                .setBaseColumnList(false)// XML columList
                .setKotlin(false) //是否生成 kotlin 代碼
                .setMapperName(Config.FILE_NAME_DAO) //自定義文件命名碉钠,注意 %s 會(huì)自動(dòng)填充表實(shí)體屬性纲缓!
                .setXmlName(Config.FILE_NAME_XML)
                .setServiceName(Config.FILE_NAME_SERVICE)
                .setServiceImplName(Config.FILE_NAME_SERVICE_IMPL)
                .setControllerName(Config.FILE_NAME_CONTROLLER)
                .setSwagger2(Config.SWAGGER_SUPPORT) // model swagger2
                ;
    }

    //實(shí)體類配置
    private static StrategyConfig strategyConfig() {
        return new StrategyConfig()
                .setChainModel(true) // 【實(shí)體】是否為構(gòu)建者模型(默認(rèn) false)
                .setNaming(NamingStrategy.underline_to_camel)
                .setColumnNaming(NamingStrategy.underline_to_camel)
                .setSuperEntityClass(BaseEntity.class)
                .setEntityLombokModel(true)
                .setRestControllerStyle(true)
                .setInclude(scanner("表名,多個(gè)英文逗號(hào)分割").split(","))
                .setControllerMappingHyphenStyle(false)
                .setEntityTableFieldAnnotationEnable(true) //是否生成實(shí)體時(shí)喊废,生成字段注解,包括@TableName("")
                ;
    }

    // 包信息配置
    private static PackageConfig packageConfig() {
        return new PackageConfig()
//                .setModuleName(scanner("模塊名"))
                .setParent(Config.PACKAGE_PARENT)
                // 如果是單體項(xiàng)目請(qǐng)注釋掉 .setModuleName(scanner("模塊名"))即可色徘,把下面注釋取消
                 .setController(Config.PACKAGE_NAME_CONTROLLER)
                 .setEntity(Config.PACKAGE_NAME_MODEL)
                 .setMapper(Config.PACKAGE_NAME_DAO)
                 .setService(Config.PACKAGE_NAME_SERVICE)
                 .setServiceImpl(Config.PACKAGE_NAME_SERVICE_IMPL)
                ;
    }

    private static InjectionConfig injectionConfig() {
        InjectionConfig injectionConfig = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定義輸出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定義配置會(huì)被優(yōu)先輸出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸出文件名 , 如果你 Entity 設(shè)置了前后綴操禀、此處注意 xml 的名稱會(huì)跟著發(fā)生變化!横腿!
                return Config.projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        injectionConfig.setFileOutConfigList(focList);
        return injectionConfig;
    }

    private static TemplateConfig templateConfig() {
        TemplateConfig templateConfig = new TemplateConfig();
        //配置自定義輸出模板颓屑,指定自定義模板路徑,注意不要帶上.ftl/.vm, 會(huì)根據(jù)使用的模板引擎自動(dòng)識(shí)別
        templateConfig.setController("templates/controllerGenerator.java");
        templateConfig.setServiceImpl("templates/serviceImplGenerator.java");
        templateConfig.setMapper("templates/mapperGenerator.java");
        templateConfig.setXml(null);
        return templateConfig;

    }

    // 獲取模板引擎
    private static AbstractTemplateEngine getTemplateEngine() {
        String templateEngine = Config.TEMPLATE_ENGINE;
        switch (templateEngine) {
            case "velocity":
                return new VelocityTemplateEngine();
            case "freemarker":
                return new FreemarkerTemplateEngine();
            case "beetl":
                return new BeetlTemplateEngine();
            default:
                return new VelocityTemplateEngine();
        }
    }

    // 執(zhí)行器
    public static void execute() {
        GlobalConfig globalConfig = globalConfig();
        DataSourceConfig dataSourceConfig = dataSourceConfig();
        PackageConfig packageConfig = packageConfig();
        StrategyConfig strategyConfig = strategyConfig();
        InjectionConfig injectionConfig = injectionConfig();
        AbstractTemplateEngine templateEngine = getTemplateEngine();
        new AutoGenerator()
                .setGlobalConfig(globalConfig)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageConfig)
                .setTemplateEngine(templateEngine)
                .setCfg(injectionConfig)
                .setTemplate(templateConfig())
                .execute();
    }

}

修改自己想要的模板耿焊,在resource目錄下新建templates目錄揪惦,然后存放所有的模板
mapperGenerator.java.ftl

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};
import org.springframework.stereotype.Repository;

/**
 * <p>
 * ${table.comment!} Mapper 接口
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Repository
<#if kotlin>
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}
</#if>

serviceImplGenerator.java.ftl

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * ${table.comment!} 服務(wù)實(shí)現(xiàn)類
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Slf4j
@Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {

}
<#else>
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {

}
</#if>

controllerGenerator.java.ftl

package ${package.Controller};

import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RequestMapping;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>

/**
 * <p>
 * ${table.comment!} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("/api/mp-generator<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
@Api(value = "/api/mp-generator<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>", tags = {"${table.comment!}接口"})
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>

}
</#if>

4. 添加一個(gè)啟動(dòng)類運(yùn)行

package com.mp.generator;


import com.mp.generator.utils.CommonUtils;

public class MySQLCodeGenerator {

    public static void main(String[] args) {
        CommonUtils.execute();
    }
}

sql腳本

/*
 Navicat Premium Data Transfer

 Source Server         : 本地
 Source Server Type    : MySQL
 Source Server Version : 50729
 Source Host           : 127.0.0.1:3306
 Source Schema         : dynamic1

 Target Server Type    : MySQL
 Target Server Version : 50729
 File Encoding         : 65001

 Date: 18/03/2021 19:02:02
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user_info
-- ----------------------------
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `available` int(1) NULL DEFAULT 1 COMMENT '是否可用,1 可用罗侯,0 不可用',
  `create_time` datetime(0) NULL DEFAULT NULL COMMENT '創(chuàng)建時(shí)間',
  `deleted` int(1) NULL DEFAULT 0 COMMENT '是否刪除器腋,0 未刪除, 1 刪除',
  `update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改時(shí)間',
  `avatar` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '頭像',
  `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '郵箱',
  `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密碼',
  `phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手機(jī)號(hào)',
  `salt` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '鹽',
  `sex` int(1) NULL DEFAULT NULL COMMENT '性別 0未知 1女 2男',
  `user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '姓名',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `user_info_user_name`(`user_name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 31 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用戶信息表' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user_info
-- ----------------------------
INSERT INTO `user_info` VALUES (1, 1, '2021-01-13 13:30:32', 0, '2021-01-15 15:19:15', NULL, '1111@qq.com', '55555', '1234567890', NULL, 0, 'testd57fdf65-6dea-44ae-8493-59bfb93dfec611111');
INSERT INTO `user_info` VALUES (2, 1, '2021-01-13 13:30:32', 0, '2021-01-15 15:19:15', NULL, '1111@qq.com', '55555', '1234567890', NULL, 0, 'test3ef83e0c-d20d-498d-852d-052bab06199922222');

SET FOREIGN_KEY_CHECKS = 1;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末钩杰,一起剝皮案震驚了整個(gè)濱河市纫塌,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌讲弄,老刑警劉巖措左,帶你破解...
    沈念sama閱讀 222,104評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異避除,居然都是意外死亡怎披,警方通過查閱死者的電腦和手機(jī)胸嘁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來凉逛,“玉大人性宏,你說我怎么就攤上這事∽捶桑” “怎么了毫胜?”我有些...
    開封第一講書人閱讀 168,697評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長昔瞧。 經(jīng)常有香客問我指蚁,道長,這世上最難降的妖魔是什么自晰? 我笑而不...
    開封第一講書人閱讀 59,836評(píng)論 1 298
  • 正文 為了忘掉前任凝化,我火速辦了婚禮,結(jié)果婚禮上酬荞,老公的妹妹穿的比我還像新娘搓劫。我一直安慰自己,他們只是感情好混巧,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,851評(píng)論 6 397
  • 文/花漫 我一把揭開白布枪向。 她就那樣靜靜地躺著,像睡著了一般咧党。 火紅的嫁衣襯著肌膚如雪秘蛔。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,441評(píng)論 1 310
  • 那天傍衡,我揣著相機(jī)與錄音深员,去河邊找鬼。 笑死蛙埂,一個(gè)胖子當(dāng)著我的面吹牛倦畅,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播绣的,決...
    沈念sama閱讀 40,992評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼叠赐,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了屡江?” 一聲冷哼從身側(cè)響起芭概,我...
    開封第一講書人閱讀 39,899評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎惩嘉,沒想到半個(gè)月后谈山,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,457評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡宏怔,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,529評(píng)論 3 341
  • 正文 我和宋清朗相戀三年奏路,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了畴椰。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,664評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡鸽粉,死狀恐怖斜脂,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情触机,我是刑警寧澤帚戳,帶...
    沈念sama閱讀 36,346評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站儡首,受9級(jí)特大地震影響片任,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜蔬胯,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,025評(píng)論 3 334
  • 文/蒙蒙 一对供、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧氛濒,春花似錦产场、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至骗奖,卻和暖如春确徙,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背执桌。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評(píng)論 1 272
  • 我被黑心中介騙來泰國打工鄙皇, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人鼻吮。 一個(gè)月前我還...
    沈念sama閱讀 49,081評(píng)論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像较鼓,于是被迫代替她去往敵國和親椎木。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,675評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容