springboot整合mybatis-plus逆向工程的實(shí)現(xiàn)
MyBatis-Plus(簡(jiǎn)稱 MP)是一個(gè) MyBatis 的增強(qiáng)工具,在 MyBatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開(kāi)發(fā)、提高效率而生。官方文檔
代碼生成器
AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過(guò) AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個(gè)模塊的代碼,極大的提升了開(kāi)發(fā)效率。
mybatis-plus是根據(jù)數(shù)據(jù)庫(kù)表來(lái)生成對(duì)應(yīng)的實(shí)體類,首先我們創(chuàng)建數(shù)據(jù)庫(kù)表User
| id | name | age | |
|---|---|---|---|
| 1 | Jone | 18 | test1@baomidou.com |
| 2 | Jack | 20 | test2@baomidou.com |
| 3 | Tom | 28 | test3@baomidou.com |
| 4 | Sandy | 21 | test4@baomidou.com |
| 5 | Billie | 24 | test5@baomidou.com |
其對(duì)應(yīng)的數(shù)據(jù)庫(kù) Schema 腳本如下:
DROP TABLE IF EXISTS user; CREATE TABLE user ( id BIGINT(20) NOT NULL COMMENT '主鍵ID', name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名', age INT(11) NULL DEFAULT NULL COMMENT '年齡', email VARCHAR(50) NULL DEFAULT NULL COMMENT '郵箱', PRIMARY KEY (id) );
其對(duì)應(yīng)的數(shù)據(jù)庫(kù) Data 腳本如下:
DELETE FROM user; INSERT INTO user (id, name, age, email) VALUES (1, 'Jone', 18, 'test1@baomidou.com'), (2, 'Jack', 20, 'test2@baomidou.com'), (3, 'Tom', 28, 'test3@baomidou.com'), (4, 'Sandy', 21, 'test4@baomidou.com'), (5, 'Billie', 24, 'test5@baomidou.com');
初始化springboot工程

其中mpconfig就是我們逆向工程配置文件
基本依賴如下:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies>
下面開(kāi)始引入逆向工程依賴
MyBatis-Plus 從 3.0.3 之后移除了代碼生成器與模板引擎的默認(rèn)依賴,需要手動(dòng)添加相關(guān)依賴:
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.1</version> </dependency> <!--添加 代碼生成器 依賴--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.1.1</version> </dependency>
添加 模板引擎 依賴,MyBatis-Plus 支持 Velocity(默認(rèn))、Freemarker、Beetl,用戶可以選擇自己熟悉的模板引擎,如果都不滿足您的要求,可以采用自定義模板引擎。
Velocity(默認(rèn)):
<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.1</version> </dependency>
Freemarker:
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> </dependency>
這里我選擇Freemarker
注意!如果您選擇了非默認(rèn)引擎,需要在 AutoGenerator 中 設(shè)置模板引擎
全部依賴如下:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- freemarker 模板引擎 --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.1</version> </dependency> <!--添加 代碼生成器 依賴--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.1.1</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies>
下面開(kāi)始:創(chuàng)建逆向工程配置類mpconfig
package com.jiangfeixiang.mpdemo.mpconfig;
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.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.*;
/**
* @ProjectName: mybatis-plus
* @Package: com.jiangfeixiang.mybatisplus.mpconfig
* @ClassName: CodeGenerator
* @Author: jiangfeixiang
* @email: 1016767658@qq.com
* @Description: 代碼生成器
* @Date: 2019/5/10/0010 21:41
*/
public class CodeGenerator {
/**
* 讀取控制臺(tái)內(nèi)容
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("請(qǐng)輸入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("請(qǐng)輸入正確的" + tip + "!");
}
public static void main(String[] args) {
/**
* 代碼生成器
*/
AutoGenerator mpg = new AutoGenerator();
/**
* 全局配置
*/
GlobalConfig globalConfig = new GlobalConfig();
//生成文件的輸出目錄
String projectPath = System.getProperty("user.dir");
globalConfig.setOutputDir(projectPath + "/src/main/java");
//Author設(shè)置作者
globalConfig.setAuthor("姜飛祥");
//是否覆蓋文件
globalConfig.setFileOverride(true);
//生成后打開(kāi)文件
globalConfig.setOpen(false);
mpg.setGlobalConfig(globalConfig);
/**
* 數(shù)據(jù)源配置
*/
DataSourceConfig dataSourceConfig = new DataSourceConfig();
// 數(shù)據(jù)庫(kù)類型,默認(rèn)MYSQL
dataSourceConfig.setDbType(DbType.MYSQL);
//自定義數(shù)據(jù)類型轉(zhuǎn)換
dataSourceConfig.setTypeConvert(new MySqlTypeConvert());
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mp?characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false");
dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("1234");
mpg.setDataSource(dataSourceConfig);
/**
* 包配置
*/
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模塊名"));
//父包名。如果為空,將下面子包名必須寫全部, 否則就只需寫子包名
pc.setParent("com.jiangfeixiang.mpdemo");
mpg.setPackageInfo(pc);
/**
* 自定義配置
*/
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
/**
* 模板
*/
//如果模板引擎是 freemarker
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 projectPath + "/src/main/resources/mapper/"+ pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
/**
* 配置模板
*/
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定義輸出模板
//指定自定義模板路徑,注意不要帶上.ftl/.vm, 會(huì)根據(jù)使用的模板引擎自動(dòng)識(shí)別
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
/**
* 策略配置
*/
StrategyConfig strategy = new StrategyConfig();
//設(shè)置命名格式
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setInclude(scanner("表名,多個(gè)英文逗號(hào)分割").split(","));
//實(shí)體是否為lombok模型(默認(rèn) false)
strategy.setEntityLombokModel(true);
//生成 @RestController 控制器
strategy.setRestControllerStyle(true);
//設(shè)置自定義繼承的Entity類全稱,帶包名
//strategy.setSuperEntityClass("com.jiangfeixiang.mpdemo.BaseEntity");
//設(shè)置自定義繼承的Controller類全稱,帶包名
//strategy.setSuperControllerClass("com.jiangfeixiang.mpdemo.BaseController");
//設(shè)置自定義基礎(chǔ)的Entity類,公共字段
strategy.setSuperEntityColumns("id");
//駝峰轉(zhuǎn)連字符
strategy.setControllerMappingHyphenStyle(true);
//表名前綴
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
拆分詳解如下:
/**
* 讀取控制臺(tái)內(nèi)容
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("請(qǐng)輸入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("請(qǐng)輸入正確的" + tip + "!");
}
讀取控制臺(tái)內(nèi)容無(wú)需更改,因?yàn)樯院髥?dòng)main方法只會(huì)需要在控制臺(tái)輸入模塊名以及數(shù)據(jù)庫(kù)表名。官網(wǎng)參考
接下來(lái)是main方法,這個(gè)也是主程序,逆向工程啟動(dòng)方法。下面看一下配置
AutoGenerator mpg = new AutoGenerator();
代碼生成器,所有的配置都需要set進(jìn)去
全局配置:
GlobalConfig globalConfig = new GlobalConfig();
//生成文件的輸出目錄(下面兩行無(wú)需改動(dòng))
String projectPath = System.getProperty("user.dir");
globalConfig.setOutputDir(projectPath + "/src/main/java");
//Author設(shè)置作者
globalConfig.setAuthor("姜飛祥");
//是否覆蓋文件
globalConfig.setFileOverride(true);
//生成后打開(kāi)文件
globalConfig.setOpen(false);
//set進(jìn)去代碼生成器對(duì)象中
mpg.setGlobalConfig(globalConfig);
數(shù)據(jù)源配置
DataSourceConfig dataSourceConfig = new DataSourceConfig();
// 數(shù)據(jù)庫(kù)類型,默認(rèn)MYSQL
dataSourceConfig.setDbType(DbType.MYSQL);
//自定義數(shù)據(jù)類型轉(zhuǎn)換
dataSourceConfig.setTypeConvert(new MySqlTypeConvert());
//驅(qū)動(dòng),URL,用戶名以及密碼配置,這里使用的是mysql5.6版本
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mp?characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false");
dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("1234");
//set進(jìn)去代碼生成器對(duì)象中
mpg.setDataSource(dataSourceConfig);
包配置
PackageConfig pc = new PackageConfig();
//這里的模塊名需要在控制臺(tái)輸入的,即生成的代碼在哪個(gè)包下
pc.setModuleName(scanner("模塊名"));
//父包名。如果為空子包名必須寫全部, 否則就只需寫子包名
pc.setParent("com.jiangfeixiang.mpdemo");
//set進(jìn)去代碼生成器對(duì)象中
mpg.setPackageInfo(pc);
上面父包名是根據(jù)工程路徑來(lái)的,如下參考:

自定義配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
自定義輸出配置
String templatePath = "/templates/mapper.xml.ftl";
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 projectPath + "/src/main/resources/mapper/"+ pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
//這塊是set到上面自定義配置中
cfg.setFileOutConfigList(focList);
//set進(jìn)去代碼生成器對(duì)象中
mpg.setCfg(cfg);
最后是策略配置
StrategyConfig strategy = new StrategyConfig();
//設(shè)置命名格式
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setInclude(scanner("表名,多個(gè)英文逗號(hào)分割").split(","));
//實(shí)體是否為lombok模型(默認(rèn) false)
strategy.setEntityLombokModel(true);
//生成 @RestController 控制器
strategy.setRestControllerStyle(true);
//設(shè)置自定義繼承的Entity類全稱,帶包名
//strategy.setSuperEntityClass("com.jiangfeixiang.mpdemo.BaseEntity");
//設(shè)置自定義繼承的Controller類全稱,帶包名
//strategy.setSuperControllerClass("com.jiangfeixiang.mpdemo.BaseController");
//設(shè)置自定義基礎(chǔ)的Entity類,公共字段
strategy.setSuperEntityColumns("id");
//駝峰轉(zhuǎn)連字符
strategy.setControllerMappingHyphenStyle(true);
//表名前綴
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
以上全部配置好之后直接啟動(dòng)main方法,之后進(jìn)入控制臺(tái)

我的模塊名是springbootmp,因?yàn)槲矣袃蓮埍?,輸入兩個(gè)表的名稱回車即可生成對(duì)應(yīng)的代碼,所生成的代碼在模塊名springbootmp下
正確執(zhí)行控制臺(tái)輸出如下

然后看一下模塊:

xxxmapper.xml文件是空的:

實(shí)體類已經(jīng)加上@Data注解省略了get/set方法并序列化

mapper接口繼承了BaseMapper

接口中沒(méi)有數(shù)據(jù)的增刪改查方法,那么我們直接在UserController類中注入IUserService接口,查詢所有user看看有沒(méi)有輸出:
@RestController
@RequestMapping("/springbootmp/user")
public class UserController {
@Autowired
private IUserService iUserService;
/**
* 獲取所有User
* @return
*/
@RequestMapping("/getAllUser")
public List<User> getAllUser(){
List<User> list = iUserService.list();
return list;
}
}
項(xiàng)目運(yùn)行直接報(bào)錯(cuò)如下:

原因是因?yàn)橹鞒绦蛑袥](méi)有加入@MapperScan("com.jiangfeixiang.mpdemo.springbootmp.mapper")

引入即可。之后重新運(yùn)行啟動(dòng)成功控制臺(tái)如下圖:

還有mybatisplus是不是很漂亮。
調(diào)用接口測(cè)試如下

到此這篇關(guān)于springboot整合mybatis-plus逆向工程的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)springboot mybatis-plus逆向工程內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot如何使用MyBatisPlus逆向工程自動(dòng)生成代碼
- springboot3.0整合mybatis-flex實(shí)現(xiàn)逆向工程的示例代碼
- SpringBoot整合MybatisPlusGernerator實(shí)現(xiàn)逆向工程
- Spring Boot整合MybatisPlus逆向工程(MySQL/PostgreSQL)
- mybatis逆向工程與分頁(yè)在springboot中的應(yīng)用及遇到坑
- SpringBoot整合MyBatis逆向工程及 MyBatis通用Mapper實(shí)例詳解
- 淺析Spring和MyBatis整合及逆向工程
- spring和Mybatis逆向工程的實(shí)現(xiàn)
相關(guān)文章
java web將數(shù)據(jù)導(dǎo)出為pdf格式文件代碼片段
這篇文章主要為大家詳細(xì)介紹了java web將數(shù)據(jù)導(dǎo)出為pdf格式文件代碼片段,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01
Spring Security介紹及配置實(shí)現(xiàn)代碼
Spring Security是一個(gè)功能強(qiáng)大的Java安全框架,它提供了全面的安全認(rèn)證(Authentication)和授權(quán)(Authorization)的支持,這篇文章給大家介紹Spring Security介紹及配置實(shí)現(xiàn)代碼,感興趣的朋友一起看看吧2025-05-05
SpringSecurity?默認(rèn)登錄認(rèn)證的實(shí)現(xiàn)原理解析
這篇文章主要介紹了SpringSecurity?默認(rèn)登錄認(rèn)證的實(shí)現(xiàn)原理解析,本文通過(guò)圖文示例相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-12-12
解決springdataJPA對(duì)原生sql支持的問(wèn)題
這篇文章主要介紹了解決springdataJPA對(duì)原生sql支持的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
java增強(qiáng)for循環(huán)的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇java增強(qiáng)for循環(huán)的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-09-09
Java 數(shù)據(jù)庫(kù)連接池c3p0 介紹
這篇文章主要介給大家分享了 Java 數(shù)據(jù)庫(kù)連接池c3p0 介紹,c3p0 是一個(gè)成熟的、高并發(fā)的 JDBC 連接池庫(kù),支持緩存和 PreparedStatements 的重用。它以LGPL v.2.1或EPL v.1.0授權(quán),下面我們就一起來(lái)看看文章內(nèi)容的詳細(xì)介紹吧,需要的朋友也可以參考一下2021-11-11
SpringBoot+layuimini實(shí)現(xiàn)左側(cè)菜單動(dòng)態(tài)展示的示例代碼
Layuimini是Layui的升級(jí)版,它是專業(yè)做后臺(tái)頁(yè)面的框架,而且是適合PC端和移動(dòng)端,以下地址可以在PC端顯示,也可以在手機(jī)上顯示,只不過(guò)會(huì)做自適應(yīng),本文將給大家介紹了SpringBoot+layuimini實(shí)現(xiàn)左側(cè)菜單動(dòng)態(tài)展示的方法,需要的朋友可以參考下2024-04-04

