前言
這篇文章將記錄我學(xué)習(xí)了解Mybatis-Plus代碼生成器相關(guān)知識。其中用到了spring-boot框架、mysql數(shù)據(jù)庫、mybatis-plus、lombok插件、API文檔框架Swagger。
Mybatis-Plus代碼生成器簡述
在后端項(xiàng)目中經(jīng)常需要?jiǎng)?chuàng)建Entity、Mapper、Service、Controller 、Mapper.xml文件,存在兩個(gè)主要缺點(diǎn):
- 這個(gè)過程中手動(dòng)創(chuàng)建有時(shí)會(huì)容易出錯(cuò),比如Entity類名寫錯(cuò)或是類里面的某個(gè)對應(yīng)數(shù)據(jù)庫表字段的變量名字寫錯(cuò)。
- 這個(gè)過程經(jīng)常反復(fù)操作、比較繁瑣、而且根本就是機(jī)械式操作。
為了節(jié)省開發(fā)時(shí)間,baomidou團(tuán)隊(duì)給mybatis-plus添加了代碼生成器類AutoGenerator,通過 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個(gè)模塊的代碼,極大的提升了開發(fā)效率。
實(shí)現(xiàn)步驟
下面我引入在項(xiàng)目中用到的代碼生成器
一. 添加相關(guān)依賴
在pom.xml導(dǎo)入代碼生成器依賴
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>latest-version</version>
</dependency>
項(xiàng)目中用到了freemarker模板引擎,導(dǎo)入依賴
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
其實(shí)MyBatis-Plus 支持 Velocity(默認(rèn))、Freemarker、Beetl,用戶可以選擇自己熟悉的模板引擎。
二. 創(chuàng)建mybatis-plus代碼生成器執(zhí)行類
創(chuàng)建目錄,這個(gè)類命名為CodeGenerator
項(xiàng)目結(jié)構(gòu).PNG
三. 在GodeGenerator中編寫相關(guān)配置代碼
package com.wzubi.maxmoney.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.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.Collections;
import java.util.Scanner;
/**
* @author jq
* @since 2019-12-24
*/
public class CodeGenerator {
/**
* <p>
* 讀取控制臺內(nèi)容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("請輸入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("請輸入正確的" + tip + "!");
}
public static void main(String[] args) {
// 代碼生成器
AutoGenerator autoGenerator = new AutoGenerator();
// 數(shù)據(jù)源配置
autoGenerator.setDataSource(new DataSourceConfig()
.setDriverName("com.mysql.cj.jdbc.Driver")
// 設(shè)置數(shù)據(jù)庫類型
.setDbType(DbType.MYSQL)
// 數(shù)據(jù)庫連接賬戶和密碼
.setUsername("root")
.setPassword("root")
// 數(shù)據(jù)庫連接的url
.setUrl("jdbc:mysql://localhost:3306/max-money?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&useAffectedRows=true&serverTimezone=CTT")
// 類型轉(zhuǎn)換,默認(rèn)由 dbType 類型決定選擇對應(yīng)數(shù)據(jù)庫內(nèi)置實(shí)現(xiàn),實(shí)現(xiàn) ITypeConvert 接口自定義數(shù)據(jù)庫 字段類型 轉(zhuǎn)換為自己需要的 java 類型
.setTypeConvert(new MySqlTypeConvert() {
@Override
public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
System.out.println("轉(zhuǎn)換類型:" + fieldType);
String t = fieldType.toLowerCase();
if (t.contains("tinyint(1)")) {
return DbColumnType.INTEGER;
}
return super.processTypeConvert(globalConfig, fieldType);
}
})
);
String projectPath = System.getProperty("user.dir");
// 全局配置
autoGenerator.setGlobalConfig(new GlobalConfig()
// 輸出目錄
.setOutputDir(projectPath+ "/src/main/java")
// 是否覆蓋
.setFileOverride(true)
//swagger注解
.setSwagger2(true)
// 時(shí)間格式
.setDateType(DateType.ONLY_DATE)
// 開啟AR模式
.setActiveRecord(false)
// XML二級緩存
.setEnableCache(false)
// 生成ResultMap
.setBaseResultMap(true)
// 生成 sql片段
.setBaseColumnList(true)
// 自動(dòng)打開生成后的文件夾
.setOpen(false)
// 所有文件的生成者
.setAuthor("jq")
);
// 包配置
PackageConfig packageConfig = new PackageConfig()
// 基本包路徑
.setParent("com.wzubi.maxmoney")
.setModuleName(scanner("模塊名"))
// 設(shè)置Mapper包名
.setMapper("dao");
autoGenerator.setPackageInfo(packageConfig);
// 策略配置
autoGenerator.setStrategy(new StrategyConfig()
// 需要生成的表
.setInclude(scanner("表名"))
// 實(shí)體類使用Lombok
.setEntityLombokModel(true)
// 表名生成策略,下劃線轉(zhuǎn)駝峰
.setNaming(NamingStrategy.underline_to_camel)
// 字段名生成策略,下劃線轉(zhuǎn)駝峰
.setColumnNaming(NamingStrategy.underline_to_camel)
// 可以繼承父實(shí)體類,沒有可以不用配置
.setSuperEntityClass("com.wzubi.maxmoney.parent.entity.BaseEntity")
// 自定義基礎(chǔ)的Entity類的公共字段
.setSuperEntityColumns("id","deleted","create_time","update_time")
// 生成 @RestController 控制器
.setRestControllerStyle(true)
// 駝峰轉(zhuǎn)連字符
.setControllerMappingHyphenStyle(true)
// 邏輯刪除屬性名稱
.setLogicDeleteFieldName("deleted")
);
// 注入自定義配置
autoGenerator.setCfg(new InjectionConfig() {
@Override
public void initMap() {
// Map<String, Object> map = new HashMap<>(1);
// map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
// this.setMap(map);
}
}.setFileOutConfigList(Collections.singletonList(
new FileOutConfig("/templates/mapper.xml.ftl") {
// 自定義Mapper.xml輸出路徑
@Override
public String outputFile(TableInfo tableInfo) {
return projectPath + "/src/main/resources/mapper/" + packageConfig.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
})));
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 不生成xml文件
templateConfig.setXml(null);
autoGenerator.setTemplate(templateConfig);
// 選擇了非默認(rèn)引擎,需要在 AutoGenerator 中 設(shè)置模板引擎
autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());
autoGenerator.execute();
}
}
總結(jié):在個(gè)類中主要配置:
- 數(shù)據(jù)庫源配置DataSourceConfig
- 數(shù)據(jù)庫表配置StrategyConfig
- 包名配置PackageConfig
- 模板配置TemplateConfig
- 全局配置GlobalConfig
- 自定義注入配置InjectionConfig
4. 執(zhí)行結(jié)果
啟動(dòng)CodeGenerator,輸入以下你想要的模塊名,和數(shù)據(jù)庫表名
代碼演示1.PNG
然后回車,生成代碼完成,如圖:
代碼演示2.PNG
代碼演示3.PNG
借用官方的動(dòng)圖演示:

動(dòng)圖演示