簡介
MyBatis-Plus(簡稱 MP)是一個 MyBatis的增強工具柬帕,在 MyBatis 的基礎(chǔ)上只做增強不做改變,為簡化開發(fā)狡门、提高效率而生
愿景
我們的愿景是成為 MyBatis 最好的搭檔陷寝,就像 魂斗羅 中的 1P、2P其馏,基友搭配凤跑,效率翻倍。
特性
- 無侵入:只做增強不做改變叛复,引入它不會對現(xiàn)有工程產(chǎn)生影響仔引,如絲般順滑
- 損耗小:啟動即會自動注入基本 CURD扔仓,性能基本無損耗,直接面向?qū)ο蟛僮?/li>
- 強大的 CRUD 操作:內(nèi)置通用 Mapper咖耘、通用 Service翘簇,僅僅通過少量配置即可實現(xiàn)單表大部分 CRUD 操作,更有強大的條件構(gòu)造器儿倒,滿足各類使用需求
- 支持 Lambda 形式調(diào)用:通過 Lambda 表達式版保,方便的編寫各類查詢條件,無需再擔(dān)心字段寫錯
- 支持主鍵自動生成:支持多達 4 種主鍵策略(內(nèi)含分布式唯一 ID 生成器 - Sequence)夫否,可自由配置彻犁,完美解決主鍵問題
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式調(diào)用,實體類只需繼承 Model 類即可進行強大的 CRUD 操作
- 支持自定義全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 內(nèi)置代碼生成器:采用代碼或者 Maven 插件可快速生成 Mapper 慷吊、 Model 袖裕、 Service 、 Controller 層代碼溉瓶,支持模板引擎急鳄,更有超多自定義配置等您來使用
- 內(nèi)置分頁插件:基于 MyBatis 物理分頁,開發(fā)者無需關(guān)心具體操作堰酿,配置好插件之后疾宏,寫分頁等同于普通 List 查詢
- 分頁插件支持多種數(shù)據(jù)庫:支持 MySQL、MariaDB触创、Oracle坎藐、DB2、H2哼绑、HSQL岩馍、SQLite、Postgre抖韩、SQLServer 等多種數(shù)據(jù)庫
- 內(nèi)置性能分析插件:可輸出 Sql 語句以及其執(zhí)行時間蛀恩,建議開發(fā)測試時啟用該功能,能快速揪出慢查詢
- 內(nèi)置全局?jǐn)r截插件:提供全表 delete 茂浮、 update 操作智能分析阻斷双谆,也可自定義攔截規(guī)則,預(yù)防誤操作
框架結(jié)構(gòu)
快速入門
創(chuàng)建數(shù)據(jù)庫表(mybatis——plus)
創(chuàng)建user表**
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)
);
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初始化!
導(dǎo)入依賴
<!-- 數(shù)據(jù)庫驅(qū)動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus -->
<!-- 只用mybatis-plus即可幌羞,不用再導(dǎo)入mybatis -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
- yml文件中配置數(shù)據(jù)庫**
spring:
datasource:
password: 123456
username: root
url: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
driver-class-name: com.mysql.jdbc.Driver
編寫pojo類寸谜,mapper接口**
pojo
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
-
mapper接口,繼承BaseMapper
@Repository //代表是持久層 public interface UserMapper extends BaseMapper<User> { //里面不需要寫東西 }
-
啟動類添加mapper掃描
@MapperScan("com.alan.mybatis.plus.mapper")
-
在測試類中測試
@SpringBootTest class MybatisPlusApplicationTests { @Autowired private UserMapper userMapper; @Test void contextLoads() { //查詢 List<User> users = userMapper.selectList(null); users.forEach(System.out::println); } }
-
結(jié)果
添加日志
-
配置yml
mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
-
結(jié)果
CRUD擴展
插入操作
Insert插入
@Test
public void testInsert(){
User user = new User();
user.setName("圖靈");
user.setAge(20);
user.setEmail("123345567@qq.com");
//result是影響行數(shù)
int result = userMapper.insert(user);
System.out.println(result);
//會自動id回填新翎,默認(rèn)雪花算法
System.out.println(user);
}
數(shù)據(jù)庫插入的id的默認(rèn)值為:全局的唯一的id
主鍵生成策略
1程帕、雪花算法:
snowflake是Twitter開源的分布式ID生成算法住练,結(jié)果是一個long型的ID。其核心思想是:使用41bit作為
毫秒數(shù)愁拭,10bit作為機器的ID(5個bit是數(shù)據(jù)中心讲逛,5個bit的機器ID),12bit作為毫秒內(nèi)的流水號(意味
著每個節(jié)點在每毫秒可以產(chǎn)生 4096 個 ID)岭埠,最后還有一個符號位盏混,永遠(yuǎn)是0∠郏可以保證幾乎全球唯
一许赃!
2、主鍵自增
2.1 需要在實體類字段上添加
@TableId(type = IdType.AUTO)
2.2 數(shù)據(jù)庫對應(yīng)的字段一定要是自增的
2.3結(jié)果
其他的源碼解釋
public enum IdType {
AUTO(0),//數(shù)據(jù)庫id自增
NONE(1),//未設(shè)置主鍵
INPUT(2),//手動輸入
ID_WORKER(3),//默認(rèn)的全局唯一id
UUID(4),//全局唯一id uuid
ID_WORKER_STR(5);//ID_WORKER 字符串表示法
}
更新操作
@Test
public void testUpdate(){
User user = new User();
user.setId(1334744418774695938L);
//這里只改年齡
user.setAge(19);
int i = userMapper.updateById(user);
System.out.println(i);
}
更新操作是動態(tài)SQL
自動填充
創(chuàng)建時間馆类、修改時間混聊!這些個操作一遍都是自動化完成的,我們不希望手動更新乾巧!
阿里巴巴開發(fā)手冊:所有的數(shù)據(jù)庫表:gmt_create句喜、gmt_modified幾乎所有的表都要配置上!而且需要自動化沟于!
代碼級別
- 修改數(shù)據(jù)庫
- 修改實體類咳胃,在時間屬性上添加注解
Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date UpdateTime;
}
@TableField(fill = FieldFill.INSERT) 在創(chuàng)建新這條數(shù)據(jù)時,更新時間旷太。
@TableField(fill = FieldFill.INSERT_UPDATE)展懈,在創(chuàng)建和更新這條數(shù)據(jù)時,更新時間供璧。
-
編寫配置類
@Slf4j @Component //該注解時把該類添加到IOC容器中 public class MyMetaObjectHandler implements MetaObjectHandler { //插入時的策略 @Override public void insertFill(MetaObject metaObject) { log.info("start insert fill....."); this.setFieldValByName("createTime",new Date(),metaObject); this.setFieldValByName("updateTime",new Date(),metaObject); } //更新時的策略 @Override public void updateFill(MetaObject metaObject) { log.info("start update fill....."); this.setFieldValByName("updateTime",new Date(),metaObject); } }
分別運行添加和修改存崖,結(jié)果:
分頁查詢
1、編寫配置類睡毒,攔截器
package com.alan.mybatis.plus.config;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* @Author Alan Ture
* @Description
*/
@Configuration
public class MyBatisPlusConfig {
/**
* 分頁插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
2金句、直接使用Page對象即可。
//分頁測試查詢
@Test
public void testPage(){
// 參數(shù)一:當(dāng)前頁
// 參數(shù)二:頁面大小
Page<User> page = new Page<>(1,5);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());
}
刪除操作
1吕嘀、根據(jù)id刪除記錄
// 測試刪除
@Test
public void testDeleteById(){
userMapper.deleteById(1334744418774695938L);
}
// 通過id批量刪除
@Test
public void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1334745985150111745L,1334745985150111746L));
}
// 通過map刪除
@Test
public void testDeleteMap() {
HashMap<String, Object> map = new HashMap<>();
map.put("name", "圖靈");
userMapper.deleteByMap(map);
}
邏輯刪除
物理刪除 :從數(shù)據(jù)庫中直接移除
邏輯刪除 :再數(shù)據(jù)庫中沒有被移除,而是通過一個變量來讓他失效贞瞒! deleted = 0 => deleted = 1
1偶房、數(shù)據(jù)庫添加字段
2、實體類添加字段军浆,并添加注解
@TableLogic//邏輯刪除
private Integer deleted;
3棕洋、配置類配置
// 邏輯刪除組件!
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
4乒融、yml配置(刪除為0掰盘,沒有刪除為1)
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
logic-delete-value: 0
logic-not-delete-value: 1
5摄悯、測試刪除
// 測試刪除
@Test
public void testDeleteById(){
userMapper.deleteById(1L);
}
實際走的是更新操作
結(jié)果
性能分析插件
我們在平時的開發(fā)中,會遇到一些慢sql愧捕。測試奢驯! druid,
作用:性能分析攔截器,用于輸出每條 SQL 語句及其執(zhí)行時間
MP也提供性能分析插件次绘,如果超過這個時間就停止運行瘪阁!
1、導(dǎo)入插件(記住邮偎,要在SpringBoot中配置環(huán)境為dev或者 test 環(huán)境管跺! )
properties.yml設(shè)置開發(fā)環(huán)境
spring:
profiles:
active: dev
/**
* SQL執(zhí)行效率插件
* 設(shè)置 dev test 環(huán)境開啟,保證我們的效率
*/
@Bean
@Profile({"dev","test"})
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new
PerformanceInterceptor();
// ms設(shè)置sql執(zhí)行的最大時間禾进,如果超過了則不執(zhí)行
performanceInterceptor.setMaxTime(10);
// 是否格式化代碼
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
2豁跑、測試使用(超過規(guī)定時間會報異常)
條件構(gòu)造器 Wrapper
我們寫一些復(fù)雜的sql就可以使用它來替代!
1泻云、測試一艇拍,isNotNull不為空,ge大于等于
@Test
public void contextLoads() {
// 查詢name不為空的用戶壶愤,并且郵箱不為空的用戶淑倾,年齡大于等于12
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age",20);
userMapper.selectList(wrapper).forEach(System.out::println);
// 和我們剛才學(xué)習(xí)的map對比一下
}
2、測試二征椒,eq查詢相等數(shù)據(jù)
@Test
public void test2(){
// 查詢名字Jone
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","Jone");
User user = userMapper.selectOne(wrapper);
// 查詢一個數(shù)據(jù)娇哆,出現(xiàn)多個結(jié)果使用List或者 Map
System.out.println(user);
}
代碼自動生成器
package com.alan.mybatis.plus;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
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.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
// 代碼自動生成器
public class GenCode {
public static void main(String[] args) {
// 需要構(gòu)建一個 代碼自動生成器 對象
AutoGenerator mpg = new AutoGenerator();
// 配置策略
// 1、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("Alan Ture");
gc.setOpen(false);
gc.setFileOverride(false); // 是否覆蓋
gc.setServiceName("%sService"); // 去Service的I前綴
gc.setIdType(IdType.ID_WORKER);
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
//2勃救、設(shè)置數(shù)據(jù)源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus? useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
//3碍讨、包的配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("blog");
pc.setParent("com.alan");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
//4、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user"); // 設(shè)置要映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true); // 自動lombok蒙秒;
strategy.setLogicDeleteFieldName("deleted");
// 自動填充配置
TableFill gmtCreate = new TableFill("create_time", FieldFill.INSERT);
TableFill gmtModified = new TableFill("update_time",
FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
// 樂觀鎖
// strategy.setVersionFieldName("version");
// strategy.setRestControllerStyle(true);
// strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2
mpg.setStrategy(strategy);
mpg.execute(); //執(zhí)行
}
}
最后
最后提供免費的Java架構(gòu)學(xué)習(xí)資料勃黍,學(xué)習(xí)技術(shù)內(nèi)容包含有:Spring,Dubbo晕讲,MyBatis, RPC, 源碼分析覆获,高并發(fā)、高性能瓢省、分布式,性能優(yōu)化弄息,微服務(wù) 高級架構(gòu)開發(fā)等等。歡迎關(guān)注我的公眾號:前程有光獲惹诨椤摹量!