Mybatis Plus代碼生成器(時(shí)間管理大師)

1. 前言
對于寫Crud的老司機(jī)來說時(shí)間非常寶貴,一些樣板代碼寫不但費(fèi)時(shí)費(fèi)力,而且枯燥無味。經(jīng)常有小伙伴問我,胖哥你怎么天天那么有時(shí)間去搞新東西,透露一下秘訣唄。

好吧,今天就把Mybatis-plus的代碼生成器分享出來,讓你也成為一個(gè)優(yōu)秀的時(shí)間管理大師。
2. 基本依賴
以Spring Boot和MySQL為例,你需要下面這些依賴:
<!-- lombok 如果不使用 需要修改代碼生成器的相關(guān)配置 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>compile</scope> </dependency> <!-- 連接池 你可以使用其它替換掉 --> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- mybatis plus starter --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> </dependency> <!-- mybatis plus 生成器模塊 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <scope>compile</scope> <optional>true</optional> </dependency> <!-- 引入freemarker包 作為代碼生成器引擎 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> <scope>compile</scope> <optional>true</optional> </dependency>
然后配置好你的數(shù)據(jù)庫,確保數(shù)據(jù)庫連接通訊暢通。
3. 定制代碼生成器
這里我期望生成的目錄結(jié)構(gòu)是這樣的:

于是我花了點(diǎn)時(shí)間定制了一些生成器的配置,代碼如下,就是這么硬核!
package cn.felord.mybatis.util;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
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.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* 代碼生成器配置
*
* @author felord
* @since 10 :39 2018/9/9
*/
public class CodeGenerator {
private String dbUrl;
private String userName;
private String password;
private String dir;
private String xmlDir;
private String packageName;
private CodeGenerator() {
}
/**
* The type Config builder.
*/
public static class ConfigBuilder {
private String dbUrl;
private String userName;
private String password;
private String dir;
private String xmlDir;
private String packageName;
/**
* Db url config builder.
*
* @param dbUrl the db url
* @return the config builder
*/
public ConfigBuilder dbUrl(final String dbUrl) {
this.dbUrl = dbUrl;
return this;
}
/**
* User name config builder.
*
* @param userName the user name
* @return the config builder
*/
public ConfigBuilder userName(final String userName) {
this.userName = userName;
return this;
}
/**
* Password config builder.
*
* @param password the password
* @return the config builder
*/
public ConfigBuilder password(final String password) {
this.password = password;
return this;
}
/**
* Dir config builder.
*
* @param dir the dir
* @return the config builder
*/
public ConfigBuilder dir(final String dir) {
this.dir = dir;
return this;
}
/**
* Dir config builder.
*
* @param xmlDir the dir
* @return the config builder
*/
public ConfigBuilder xmlDir(final String xmlDir) {
this.xmlDir = xmlDir;
return this;
}
/**
* Package name config builder.
*
* @param packageName the package name
* @return the config builder
*/
public ConfigBuilder packageName(final String packageName) {
this.packageName = packageName;
return this;
}
/**
* Build code generator.
*
* @return the code generator
*/
public CodeGenerator build() {
CodeGenerator generator = new CodeGenerator();
generator.dbUrl = Optional.of(this.dbUrl).get();
generator.userName = Optional.of(this.userName).get();
generator.password = Optional.of(this.password).get();
generator.dir = Optional.of(this.dir).get();
generator.xmlDir = Optional.of(this.xmlDir).get();
generator.packageName = Optional.of(this.packageName).get();
return generator;
}
}
/**
* Code.
*
* @param tableNames the table names
*/
public void code(String... tableNames) {
codingMysql(true, false, true, this.dbUrl, this.userName, this.password, this.dir, this.xmlDir, this.packageName, tableNames);
}
/**
*
* 生成器核心部分
*
* @param serviceNameStartWithI 是否前綴I
* @param createController 是否生成controller
* @param useLombok 是否使用 lombok
* @param dbUrl 數(shù)據(jù)庫連接
* @param username 用戶名稱
* @param password 密碼
* @param outDir 輸出目錄
* @param xmlDir xml 文件目錄
* @param packageName 包路徑
* @param tableNames 表名稱
*/
private static void codingMysql(boolean serviceNameStartWithI,
boolean createController,
boolean useLombok,
String dbUrl,
String username,
String password,
String outDir,
String xmlDir,
String packageName,
String... tableNames) {
GlobalConfig config = new GlobalConfig();
DataSourceConfig dataSourceConfig = new DataSourceConfig();
// 數(shù)據(jù)庫類型 這里使用 mysql
dataSourceConfig.setDbType(DbType.MYSQL)
.setUrl(dbUrl)
.setUsername(username)
.setPassword(password)
// 驅(qū)動名稱 這里使用mysql
.setDriverName("com.mysql.jdbc.Driver");
// 自定義xml輸出路徑
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
// 你也可以定制 xml 的模板
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義xml文件的路徑
return xmlDir + "/mapper/" + tableInfo.getMapperName() + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
// 策略配置項(xiàng)
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig
.setCapitalMode(false)
// 是否使用 lombok
.setEntityLombokModel(useLombok)
// 下劃線轉(zhuǎn)駝峰
.setNaming(NamingStrategy.underline_to_camel)
//修改替換成你需要的表名,多個(gè)表名傳數(shù)組
.setInclude(tableNames);
// 使用 AR 模式
config.setActiveRecord(true)
// 設(shè)置頭注釋的 author
.setAuthor("system")
// 項(xiàng)目輸出路徑
.setOutputDir(outDir)
// 是否覆蓋已經(jīng)生成的同名文件
.setFileOverride(true)
// 雪花算法生成id
.setIdType(IdType.ASSIGN_ID)
// 是否使用緩存
.setEnableCache(false)
// 是否生成 xml 中的 基礎(chǔ) resultMap
.setBaseResultMap(true);
if (!serviceNameStartWithI) {
// Service 層的 通用格式后綴
config.setServiceName("%sService");
}
// 實(shí)體類包名
PackageConfig packageConfig = new PackageConfig().setParent(packageName).setEntity("entity");
TemplateConfig templateConfig = new TemplateConfig().setXml(null);
// 這里選擇不生成 controller 實(shí)際上 生成的大多不符合我們需要 到服務(wù)層就行了
if (!createController) {
templateConfig.setController(null);
}
// 整合起來運(yùn)行
new AutoGenerator()
.setGlobalConfig(config)
.setTemplateEngine(new FreemarkerTemplateEngine())
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(packageConfig)
.setCfg(cfg)
.setTemplate(templateConfig)
.execute();
}
}
如果我生成的目錄結(jié)構(gòu)能夠滿足你的需要,那就巧了,直接拿去用;如果不滿足需要,你可以按照注釋的說明進(jìn)行微調(diào)。18年搞的用了好幾年,沒出過什么亂子。
4. 代碼生成器的使用
使用起來非常簡單,確保數(shù)據(jù)庫能夠使用JDBC連接成功,寫個(gè)main方法,配置一下,跑起來就是了:
/**
* @author felord.cn
* @since 11:34
**/
public class AutoCoding {
public static void main(String[] args) {
// maven 工程 main 包的全路徑
final String mainDir = "C:\\IdeaProjects\\bc-recyling\\src\\main\\";
CodeGenerator.ConfigBuilder builder = new CodeGenerator.ConfigBuilder();
CodeGenerator codeGenerator = builder
// 數(shù)據(jù)庫連接
.dbUrl("jdbc:mysql://localhost:3306/test")
// 賬戶
.userName("root")
// 密碼
.password("123456")
// 生成類位置
.dir(mainDir + "java")
// 生成xml 位置
.xmlDir(mainDir + "resources")
// 包引用路徑
.packageName("cn.felord.mybatis")
.build();
//根據(jù)表生成后臺代碼
codeGenerator.code("user_info");
}
}
然后代碼就生成了,是不是非常的好用?恭喜你獲得了 時(shí)間管理大師 榮譽(yù)稱號。
切記不要炫耀,否則需求加倍。
5. 總結(jié)
雖然好用,但是建議新手不要使用,多手寫一下代碼。另外復(fù)雜的SQL還是建議自己寫,多鍛煉寫SQL的能力。如果你在使用中有什么問題,可以私信我進(jìn)行溝通。
到此這篇關(guān)于Mybatis Plus代碼生成器(時(shí)間管理大師)的文章就介紹到這了,更多相關(guān)Mybatis Plus代碼生成器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Mybatis Plus 代碼生成器的實(shí)現(xiàn)
- MyBatisPlus3.x中使用代碼生成器(全注釋)
- MybatisPlus使用代碼生成器遇到的小問題(推薦)
- MyBatis Plus中代碼生成器使用詳解
- 基于Mybatis Plus實(shí)現(xiàn)代碼生成器CodeGenerator
- SpringBoot+MybatisPlus+代碼生成器整合示例
- Mybatis Plus 代碼生成器的實(shí)現(xiàn)
- mybatis plus代碼生成器配置過程解析
- 基于Mybatis plus 自動代碼生成器的實(shí)現(xiàn)代碼
- MyBatis-Plus代碼生成器的使用詳解
相關(guān)文章
使用String轉(zhuǎn)換到Map結(jié)構(gòu)
這篇文章主要介紹了使用String轉(zhuǎn)換到Map結(jié)構(gòu),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
推薦一款I(lǐng)ntelliJ IDEA提示快捷鍵的Key Promoter X插件
今天小編就為大家分享一篇關(guān)于IntelliJ IDEA提示快捷鍵的Key Promoter X插件,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-10-10
springboot實(shí)現(xiàn)string轉(zhuǎn)json json里面帶數(shù)組
這篇文章主要介紹了springboot實(shí)現(xiàn)string轉(zhuǎn)json json里面帶數(shù)組,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
Spring注解@Configuration與@Bean注冊組件的使用詳解
這篇文章主要介紹了SpringBoot中的注解@Configuration與@Bean注冊組件的使用,具有很好的參考價(jià)值,希望對大家有所幫助2022-06-06
快速學(xué)會Dubbo的配置環(huán)境及相關(guān)配置
本文主要講解Dubbo的環(huán)境與配置,文中運(yùn)用大量代碼和圖片講解的非常詳細(xì),需要學(xué)習(xí)或用到相關(guān)知識的小伙伴可以參考這篇文章2021-09-09
idea中解決maven包沖突的問題(maven helper)
這篇文章主要介紹了idea中解決maven包沖突的問題(maven helper),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12

