springboot 2.0 教程-13-mybatis增強mybatis-plus
閱讀原文:https://blog.bywind.cn/articles/2018/11/28/1543373589258.html
視訊教程:https://www.bilibili.com/video/av35595465
課程原始碼:https://github.com/ibywind/springboot-learn
關注公眾號 檢視更多技術乾貨
還可加群 , 眾多好基友在等你
springboot 書籍 PDF 下載
掃描關注上方公眾號
回覆關鍵字 boot
就可以下載這本書了
書籍的排版很好的,我自己也在看.大家可以一起交流哦
寫在前面
hello 大家好
歡迎大家收看御風大世界
本次課是
springboot 系列教程第13課
這節課我們將學習一個國人開發的
mybatis 增強框架
mybatis-plus
真的增強了不少啊 !!
mybatis-plus
Mybatis-Plus(簡稱MP)是一個 Mybatis 的增強工具,在 Mybatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。
我們的願景是成為
Mybatis
最好的搭檔,就像 魂鬥羅 中的1P、2P,基友搭配,效率翻倍。
特性
- 無侵入:Mybatis-Plus 在 Mybatis 的基礎上進行擴充套件,只做增強不做改變,引入 Mybatis-Plus 不會對您現有的 Mybatis 構架產生任何影響,而且 MP 支援所有 Mybatis 原生的特性
- 依賴少:僅僅依賴 Mybatis 以及 Mybatis-Spring
- 損耗小:啟動即會自動注入基本 CURD,效能基本無損耗,直接面向物件操作
- 預防Sql注入:內建 Sql 注入剝離器,有效預防Sql注入攻擊
- 通用CRUD操作:內建通用 Mapper、通用 Service,僅僅通過少量配置即可實現單表大部分 CRUD 操作,更有強大的條件構造器,滿足各類使用需求
- 多種主鍵策略:支援多達4種主鍵策略(內含分散式唯一ID生成器),可自由配置,完美解決主鍵問題
- 支援熱載入:Mapper 對應的 XML 支援熱載入,對於簡單的 CRUD 操作,甚至可以無 XML 啟動
- 支援ActiveRecord:支援 ActiveRecord 形式呼叫,實體類只需繼承 Model 類即可實現基本 CRUD 操作
- 支援程式碼生成:採用程式碼或者 Maven 外掛可快速生成 Mapper 、 Model 、 Service 、 Controller 層程式碼,支援模板引擎,更有超多自定義配置等您來使用(P.S. 比 Mybatis 官方的 Generator 更加強大!)
- 支援自定義全域性通用操作:支援全域性通用方法注入( Write once, use anywhere )
- 支援關鍵詞自動轉義:支援資料庫關鍵詞(order、key……)自動轉義,還可自定義關鍵詞
- 內建分頁外掛:基於 Mybatis 物理分頁,開發者無需關心具體操作,配置好外掛之後,寫分頁等同於普通List查詢
- 內建效能分析外掛:可輸出 Sql 語句以及其執行時間,建議開發測試時啟用該功能,能有效解決慢查詢
- 內建全域性攔截外掛:提供全表 delete 、 update 操作智慧分析阻斷,預防誤操作
架構原理
程式碼託管
快速整合
把之前的mybatis幹掉
加入這兩個依賴
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.1.9</version>
</dependency>
程式碼生成
package cn.bywind.boot;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class Generator {
public static void main(String[] args) {
// 包名
String packageName = "cn.bywind.boot";
boolean serviceNameStartWithI = false;//auth -> UserService, 設定成true: auth -> IUserService
//把需要自動生成的表 放在這裡!!
generateByTables(serviceNameStartWithI, packageName, "bywind", "boot", "person");
generateByTables(serviceNameStartWithI, packageName, "bywind", "boot", "bluetooth");
System.out.println("completed...");
}
/**
* @param serviceNameStartWithI
* @param packageName 包名
* @param author 作者
* @param database 資料庫名
* @param tableNames 表名
*/
private static void generateByTables(boolean serviceNameStartWithI, String packageName, String author, String database, String... tableNames) {
GlobalConfig config = new GlobalConfig();
String dbUrl = "jdbc:mysql://127.0.0.1:3306/" + database + "?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false";
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL)
.setUrl(dbUrl)
.setUsername("root")
.setPassword("123456")
.setDriverName("com.mysql.jdbc.Driver");
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig
.setCapitalMode(true)
.setEntityLombokModel(false)
.setDbColumnUnderline(true)
.setNaming(NamingStrategy.underline_to_camel)
// .setSuperMapperClass("cn.saytime.mapper.BaseMapper")
.setInclude(tableNames);//修改替換成你需要的表名,多個表名傳陣列
config.setActiveRecord(false)
.setAuthor(author)
.setOutputDir("d:\\codeGen")
.setFileOverride(true)
.setEnableCache(false);
if (!serviceNameStartWithI) {
config.setServiceName("%sService");
}
new AutoGenerator().setGlobalConfig(config)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(
new PackageConfig()
.setParent(packageName)
.setController("www")
.setEntity("model")
.setMapper("mapper")
.setService("service")
.setServiceImpl("service.impl")
.setXml("mappers")
).execute();
}
}
生成了好多啊 !!我們拷貝到 我們的專案中 (不建議直接生成到專案 , 萬一手滑 覆蓋了 別人的 …..)
配置properties檔案
##mybatis-plus
mybatis-plus.mapper-locations=classpath:mappers/*.xml
mybatis-plus.type-aliases-package=cn.bywind.boot.model
# 修改xml 不用重啟 除錯神器
mybatis-plus.global-config.refresh-mapper=true
測試一番
幫我們把 service實現都生成了
我們什麼都不需要寫
你看
真的什麼都不用寫
然後就可以做簡單的 單表 增刪改查了
package cn.bywind.boot;
import cn.bywind.boot.model.Person;
import cn.bywind.boot.service.PersonService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class BootApplicationTests {
@Autowired
PersonService personService;
@Autowired
RedisTemplate redisTemplate;
@Test
public void contextLoads() {
}
@Test
public void testGetPerson(){
Person person = personService.selectById(1);
System.out.println(person);
}
@Test
public void testUpdatePerson(){
Person person = new Person();
person.setId(1);
person.setName("御風大世界");
personService.updateById(person);
}
@Test
public void testRedisAdd(){
redisTemplate.opsForValue().set("name","bywind");
}
@Test
public void testGetRedisResult(){
Object name = redisTemplate.opsForValue().get("name");
System.out.println("得到redis的值:"+name);
}
@Test
public void testPage(){
Page<Person> page = new Page<>();
page.setCurrent(0);
page.setSize(10);
Page<Person> personPage = personService.selectPage(page);
System.out.println(JSON.toJSONString(personPage));
}
}
測試效果
亮點介紹
我們開啟了 分頁 外掛 和 效能監控外掛
並且 可以 設定 什麼環境下 開啟 這裡我們 dev test 開啟列印SQL執行時間
正式環境 他是不會列印的
我們的 maven 是有多個 profiles 的
分頁外掛上面我們已經演示了
這個框架還有很多其他的外掛 很好用
大家可以參看他的文件 詳細看下效果
選擇自己適合的就好
- 分頁外掛
- 執行分析外掛
- 效能分析外掛
- 樂觀鎖外掛
- XML熱載入
- 自定義全域性操作
- 公共欄位自動填充
- 邏輯刪除
- 讀寫分離 & 多資料來源
- 主鍵Sequence
- 多租戶 SQL 解析器
- 通用列舉自動注入
- Idea 快速開發外掛
感悟一下
這個外掛
我們之前 都是自己寫的
我說真的
我們自己寫 讀寫分離的 邏輯
自己寫 分頁外掛
自己寫count外掛
自己寫 帶引數列印的 SQL外掛
很懷念那個時候 生擼啊
不過現在有了這個mybatis-plus
真的很不錯
也證明了一句話
大家都需要自己寫的東西 你把他整理下 就是個框架了 !
開個玩笑
結束語
如果大家對於這裡比較感興趣的話
可以去B站檢視我的視訊講解
https://space.bilibili.com/193580090/#/
或者是在 github下載原始碼