Mybatis-Plus的使用詳解
一、特性
- 無侵入:只做增強(qiáng)不做改變,引入它不會(huì)對(duì)現(xiàn)有工程產(chǎn)生影響,如絲般順滑
- 損耗?。?jiǎn)?dòng)即會(huì)自動(dòng)注入基本 CURD,性能基本無損耗,直接面向?qū)ο蟛僮鳎?BaseMapper
- 強(qiáng)大的 CRUD 操作:內(nèi)置通用 Mapper、通用 Service,僅僅通過少量配置即可實(shí)現(xiàn)單表大部分
- CRUD 操作,更有強(qiáng)大的條件構(gòu)造器,滿足各類使用需求, 以后簡(jiǎn)單的CRUD操作,它不用自己編寫 了!
- 支持 Lambda 形式調(diào)用:通過 Lambda 表達(dá)式,方便的編寫各類查詢條件,無需再擔(dān)心字段寫錯(cuò)
- 支持主鍵自動(dòng)生成:支持多達(dá) 4 種主鍵策略(內(nèi)含分布式唯一 ID 生成器 - Sequence),可自由配 置,完美解決主鍵問題
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式調(diào)用,實(shí)體類只需繼承 Model 類即可進(jìn)行強(qiáng)大 的 CRUD
- 操作
- 支持自定義全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 內(nèi)置代碼生成器:采用代碼或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller
- 層代碼,支持模板引擎,更有超多自定義配置等您來使用(自動(dòng)幫你生成代碼)
- 內(nèi)置分頁插件:基于 MyBatis 物理分頁,開發(fā)者無需關(guān)心具體操作,配置好插件之后,寫分頁等同 于普通 List 查詢
- 分頁插件支持多種數(shù)據(jù)庫:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、
- Postgre、SQLServer 等多種數(shù)據(jù)庫
- 內(nèi)置性能分析插件:可輸出 Sql 語句以及其執(zhí)行時(shí)間,建議開發(fā)測(cè)試時(shí)啟用該功能,能快速揪出慢 查詢
- 內(nèi)置全局?jǐn)r截插件:提供全表 delete 、 update 操作智能分析阻斷,也可自定義攔截規(guī)則,預(yù)防誤 操作
二、使用步驟
1、創(chuàng)建數(shù)據(jù)庫 mybatis_plus,創(chuàng)建表
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'); -- 真實(shí)開發(fā)中,version(樂觀鎖)、deleted(邏輯刪除)、gmt_create、gmt_modified
2、創(chuàng)建SpringBoot項(xiàng)目!
3、導(dǎo)入依賴
<!-- 數(shù)據(jù)庫驅(qū)動(dòng) --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- mybatis-plus --> <!-- mybatis-plus 是自己開發(fā),并非官方的! --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency>
4、配置
# mysql 5 驅(qū)動(dòng)不同 com.mysql.jdbc.Driver # mysql 8 驅(qū)動(dòng)不同com.mysql.cj.jdbc.Driver、需要增加時(shí)區(qū)的配置 serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus? useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
5、建實(shí)體類
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
6、mapper接口
// 在對(duì)應(yīng)的Mapper上面繼承基本的類 BaseMapper
@Repository // 代表持久層
public interface UserMapper extends BaseMapper<User> {
// 所有的CRUD操作都已經(jīng)編寫完成了
// 你不需要像以前的配置一大堆文件了!
}
7、入口類掃描dao
在主啟動(dòng)類上去掃描我們的mapper包下的所有接口
@MapperScan("com.yn.mapper")
三、配置日志
我們所有的sql現(xiàn)在是不可見的,我們希望知道它是怎么執(zhí)行的,所以我們必須要看日志!
# 配置日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

配置完畢日志之后,后面的學(xué)習(xí)就需要注意這個(gè)自動(dòng)生成的SQL,你們就會(huì)喜歡上 MyBatis-Plus!
四、CRUD擴(kuò)展
1、插入操作
@Autowired
private UserMapper userMapper;
@Test
public void testInsert() {
User user = new User();
user.setName("張三");
user.setAge(23);
user.setEmail("163.com");
int result = userMapper.insert(user);//幫我們自動(dòng)生成id
System.out.println(result);// 受影響的行數(shù)
System.out.println(user);// 發(fā)現(xiàn)id會(huì)自動(dòng)回填
}

2、主鍵生成策略
在實(shí)體類字段上 @TableId(type = IdType.xxx),一共有六種主鍵生成策略
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
/*
@TableId(type = IdType.AUTO) // 1.數(shù)據(jù)庫id自增 注意:在數(shù)據(jù)庫里字段一定要設(shè)置自增!
@TableId(type = IdType.NONE) // 2.未設(shè)置主鍵
@TableId(type = IdType.INPUT) // 3.手動(dòng)輸入
@TableId(type = IdType.ID_WORKER) // 4.默認(rèn)的全局唯一id
@TableId(type = IdType.UUID) // 5.全局唯一id uuid
@TableId(type = IdType.ID_WORKER_STR) // 6.ID_WORKER 字符串表示法
*/
private Long id;
private String name;
private Integer age;
private String email;
}
3、更新操作
@Test
public void testUpdate() {
User user = new User();
user.setId(6L);
user.setName("李四");
user.setAge(29);
user.setEmail("qq.com");
int result = userMapper.updateById(user);
}

4、自動(dòng)填充
創(chuàng)建時(shí)間、修改時(shí)間!這些個(gè)操作一遍都是自動(dòng)化完成的,我們不希望手動(dòng)更新!
阿里巴巴開發(fā)手冊(cè):所有的數(shù)據(jù)庫表:gmt_create、gmt_modified幾乎所有的表都要配置上!而且需要自動(dòng)化!
1. 方式一:數(shù)據(jù)庫級(jí)別(工作中不允許你修改數(shù)據(jù)庫)
在表中新增字段 create_time, update_time,
實(shí)體類同步
private Date createTime; private Date updateTime;
以下為操作后的變化

2. 方式二:代碼級(jí)別
1、刪除數(shù)據(jù)庫的默認(rèn)值、更新操作!

2、實(shí)體類字段屬性上需要增加注解
// 字段添加填充內(nèi)容 @TableField(fill = FieldFill.INSERT)//插入的時(shí)候操作 private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE)//插入和更新的時(shí)候都操作 private Date updateTime
3、編寫處理器來處理這個(gè)注解即可!
@Slf4j
@Component//加入spring容器
public class MuMetaObjecHandler implements MetaObjectHandler {
// 插入時(shí)的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill.....");
// setFieldValByName(String 字段名, Object 要插入的值, MetaObject meateObject);
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
// 更新時(shí)的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill.....");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
4、測(cè)試插入、更新后觀察時(shí)間!

5、樂觀鎖
樂觀鎖 : 故名思意十分樂觀,它總是認(rèn)為不會(huì)出現(xiàn)問題,無論干什么不去上鎖!如果出現(xiàn)了問題,再次更新值測(cè)試,給所有的記錄加一個(gè)version
悲觀鎖:故名思意十分悲觀,它總是認(rèn)為總是出現(xiàn)問題,無論干什么都會(huì)上鎖!再去操作!
樂觀鎖實(shí)現(xiàn)方式:
- 取出記錄時(shí),獲取當(dāng)前 version
- 更新時(shí),帶上這個(gè)version
- 執(zhí)行更新時(shí), set version = newVersion where version = oldVersion
- 如果version不對(duì),就更新失敗
樂觀鎖:1、先查詢,獲得版本號(hào) version = 1 -- A 線程 update user set name = "kuangshen", version = version + 1 where id = 2 and version = 1 -- B 線程搶先完成,這個(gè)時(shí)候 version = 2,會(huì)導(dǎo)致 A 修改失??! update user set name = "kuangshen", version = version + 1 where id = 2 and version = 1
測(cè)試一下MP的樂觀鎖插件
1、給數(shù)據(jù)庫中增加version字段!

2、實(shí)體類加對(duì)應(yīng)的字段
@Version //樂觀鎖Version注解 private Integer version;
3、注冊(cè)組件
// 掃描的 mapper 文件夾
@MapperScan("com.yn.mapper")
@EnableTransactionManagement
@Configuration // 配置類
public class MyBatisPlusConfig {
// 注冊(cè)樂觀鎖插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
3、測(cè)試
// 測(cè)試樂觀鎖成功!
@Test
public void testOptimisticLocker() {
// 1、查詢用戶信息
User user = userMapper.selectById(1L);
// 2、修改用戶信息
user.setName("kuangshen");
user.setEmail("24736743@qq.com");
// 3、執(zhí)行更新操作
userMapper.updateById(user);
}
// 測(cè)試樂觀鎖失??!多線程下
@Test
public void testOptimisticLocker2() {
// 線程 1
User user = userMapper.selectById(1L);
user.setName("kuangshen111");
user.setEmail("24736743@qq.com");
// 模擬另外一個(gè)線程執(zhí)行了插隊(duì)操作
User user2 = userMapper.selectById(1L);
user2.setName("kuangshen222");
user2.setEmail("24736743@qq.com");
userMapper.updateById(user2);
// 自旋鎖來多次嘗試提交!
userMapper.updateById(user); // 如果沒有樂觀鎖就會(huì)覆蓋插隊(duì)線程的值!
}

6、查詢操作
// 測(cè)試查詢
@Test
public void testSelectById() {
User user = userMapper.selectById(1L);
System.out.println(user);
}
// 測(cè)試批量查詢!
@Test
public void testSelectByBatchId() {
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
// 按條件查詢之一使用map操作
@Test
public void testSelectByBatchIds() {
HashMap<String, Object> map = new HashMap<>();
// 自定義要查詢
map.put("name", "狂神說Java");
map.put("age", 3);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
7、分頁查詢
1.配置攔截器組件
// 掃描的 mapper 文件夾
@MapperScan("com.yn.mapper")
@EnableTransactionManagement
@Configuration // 配置類
public class MyBatisPlusConfig {
// 注冊(cè)樂觀鎖插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
//分頁插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
2.直接使用Page對(duì)象即可
// 測(cè)試分頁查詢
@Test
public void testPage() {
// 參數(shù)一:當(dāng)前頁
// 參數(shù)二:頁面大小
// 使用了分頁插件之后,所有的分頁操作也變得簡(jiǎn)單的!
Page<User> page = new Page<>(2, 3);
userMapper.selectPage(page, null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());
}
8、刪除操作
// 測(cè)試刪除
@Test
public void testDeleteById() {
userMapper.deleteById(1240620674645544965L);
}
// 通過id批量刪除
@Test
public void testDeleteBatchId() {
userMapper.deleteBatchIds(Arrays.asList(1240620674645544961L, 1240620674645544962L));
}
// 通過map刪除
@Test
public void testDeleteMap() {
HashMap<String, Object> map = new HashMap<>();
map.put("name", "狂神說Java");
userMapper.deleteByMap(map);
}
9、邏輯刪除
物理刪除 :從數(shù)據(jù)庫中直接移除
邏輯刪除 :再數(shù)據(jù)庫中沒有被移除,而是通過一個(gè)變量來讓他失效! deleted = 0 => deleted = 1
管理員可以查看被刪除的記錄!防止數(shù)據(jù)的丟失,類似于回收站!
邏輯刪除步驟:
1、在數(shù)據(jù)表中增加一個(gè) deleted 字段

2、實(shí)體類中增加屬性
@TableLogic //邏輯刪除 private Integer deleted;
3、配置!
// 邏輯刪除組件!
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
# 配置邏輯刪除 mybatis-plus.global-config.db-config.logic-delete-value=1 mybatis-plus.global-config.db-config.logic-not-delete-value=0
3、查看!


10、性能分析插件
我們?cè)谄綍r(shí)的開發(fā)中,會(huì)遇到一些慢sql。
作用:性能分析攔截器,用于輸出每條 SQL 語句及其執(zhí)行時(shí)間
MP也提供性能分析插件,如果超過這個(gè)時(shí)間就停止運(yùn)行!
1、導(dǎo)入插件
/**
* * SQL執(zhí)行效率插件
*
*/
@Bean
@Profile({"dev", "test"})// 設(shè)置 dev test 環(huán)境開啟,保證我們的效率
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(100); // ms設(shè)置sql執(zhí)行的最大時(shí)間,如果超過了則不執(zhí)行
performanceInterceptor.setFormat(true); // 是否格式化代碼
return performanceInterceptor;
}
記住,要在SpringBoot中配置環(huán)境為dev或者 test 環(huán)境!
#設(shè)置開發(fā)環(huán)境 spring.profiles.active=dev
2、測(cè)試使用!
@Test
void contextLoads() {
// 參數(shù)是一個(gè) Wrapper ,條件構(gòu)造器,這里我們先不用 null
// 查詢?nèi)坑脩?
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}

11、條件構(gòu)造器
我們寫一些復(fù)雜的sql就可以使用它來替代!
@SpringBootTest
public class WrapperTest {
@Autowired
private UserMapper userMapper;
//1、測(cè)試一,記住查看輸出的SQL進(jìn)行分析
@Test
void test1() {
// 查詢name不為空的用戶,并且郵箱不為空的用戶,年齡大于等于12
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age", 12);
userMapper.selectList(wrapper).forEach(System.out::println); // 和我們剛才學(xué)習(xí)的map對(duì)比一下
}
//2、測(cè)試二
@Test
void test2() {
// 查詢名字狂神說
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "狂神說");
User user = userMapper.selectOne(wrapper); // 查詢一個(gè)數(shù)據(jù),出現(xiàn)多個(gè)結(jié)果使用List或者 Map
System.out.println(user);
}
//3、區(qū)間查詢
@Test
void test3() {
// 查詢年齡在 20 ~ 30 歲之間的用戶
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age", 20, 30); // 區(qū)間
Integer count = userMapper.selectCount(wrapper);// 查詢結(jié)果數(shù)
System.out.println(count);
}
//4、模糊查詢
@Test
void test4() {
// 查詢年齡在 20 ~ 30 歲之間的用戶
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 名字中不包含e的 和 郵箱t%
wrapper
.notLike("name", "e")
.likeRight("email", "t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}
//5、模糊查詢
@Test
void test5() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
// id 在子查詢中查出來
wrapper.inSql("id", "select id from user where id<3");
List<Object> objects = userMapper.selectObjs(wrapper);
objects.forEach(System.out::println);
}
//排序
@Test
void test6() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 通過id進(jìn)行排序
wrapper.orderByDesc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
}
12、代碼自動(dòng)生成器
AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成Entity、Mapper、Mapper XML、Service、Controller 等各個(gè)模塊的代碼,極大的提升了開發(fā)效率。
測(cè)試:
package com.yn;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
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 org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
public class Code {
public static void main(String[] args) {
// 需要構(gòu)建一個(gè) 代碼自動(dòng)生成器 對(duì)象
AutoGenerator mpg = new AutoGenerator();
// 配置策略
// 1、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");//獲取當(dāng)前的項(xiàng)目路徑
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("王六六");//作者
gc.setOpen(false);//是否打開資源管理器
gc.setFileOverride(false); // 是否覆蓋原來生成的
gc.setServiceName("%sService"); // 去Service的I前綴,生成的server就沒有前綴了
gc.setIdType(IdType.ID_WORKER); //id生成策略
gc.setDateType(DateType.ONLY_DATE);//日期的類型
gc.setSwagger2(true);//自動(dòng)配置Swagger文檔
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("root");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
//3、包的配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("blog");//模塊的名字
pc.setParent("com.yn");//放在哪個(gè)包下
pc.setEntity("entity");//實(shí)體類的包名字
pc.setMapper("mapper");//dao的包字
pc.setService("service");//server的包名
pc.setController("controller");//controller的包名
mpg.setPackageInfo(pc);
//4、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user"); // 設(shè)置要映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);//數(shù)據(jù)庫表名 下劃線轉(zhuǎn)駝峰命名
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//數(shù)據(jù)庫列的名字 下劃線轉(zhuǎn)駝峰命名
strategy.setEntityLombokModel(true); // 自動(dòng)生成 lombok;
strategy.setLogicDeleteFieldName("deleted");//邏輯刪除
// 自動(dòng)填充配置
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified", 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); //controller中鏈接請(qǐng)求:localhost:8080/hello_id_2
mpg.setStrategy(strategy);
mpg.execute(); //執(zhí)行
}
}
報(bào)錯(cuò)的可以導(dǎo)一下這個(gè)包
<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version> </dependency>
到此這篇關(guān)于Mybatis-Plus的使用詳解的文章就介紹到這了,更多相關(guān)Mybatis-Plus使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Struts2實(shí)現(xiàn)文件上傳時(shí)顯示進(jìn)度條功能
這篇文章主要為大家詳細(xì)介紹了Struts2實(shí)現(xiàn)文件上傳時(shí)顯示進(jìn)度條功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
分享我的第一次java Selenium自動(dòng)化測(cè)試框架開發(fā)過程
這篇文章主要介紹了分享我的第一次java Selenium自動(dòng)化測(cè)試框架開發(fā)過程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
Spring?Boot的幾種統(tǒng)一處理方式梳理小結(jié)
這篇文章主要為大家介紹了Spring?Boot的幾種統(tǒng)一處理方式梳理小結(jié),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05
解決Java處理HTTP請(qǐng)求超時(shí)的問題
這篇文章主要介紹了解決Java處理HTTP請(qǐng)求超時(shí)的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03
Java如何跳出當(dāng)前多重循環(huán)你知道嗎

