今天開(kāi)始接觸了MyBatis-Plus,所以來(lái)簡(jiǎn)單記錄下是如何使用的。
一、快速開(kāi)始
1.導(dǎo)入依賴
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok用來(lái)簡(jiǎn)化實(shí)體類-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
2.創(chuàng)建實(shí)體類
@Data
public class User {
/*
@TableId(type = IdType.ID_WORKER) mybatis-plus自帶的id生成策略,生成19位的值,適用于數(shù)值類型的主鍵
@TableId(type = IdType.ID_WORKER_STR) mybatis-plus自帶的id生成策略,生成19位的值,適用于字符串類型的主鍵
若是使用mybatis-plus且沒(méi)有指定主鍵生成策略,會(huì)自動(dòng)根據(jù)主鍵類型選擇生成策略
*/
private Long id;
private String name;
private Integer age;
private String email;
}
該實(shí)體類中使用了lembok,所以會(huì)自動(dòng)生成set,get方法
3.創(chuàng)建dao層
因?yàn)橹皇窍群?jiǎn)單演示下MyBatis-Plus的用法,所以這里直接先創(chuàng)建DAO層,用于單元測(cè)試
package com.atguigu.mpdemo1010.mapper;
import com.atguigu.mpdemo1010.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
/**
* @Author su mingxin
* @Date 2020/9/15 11:12
*
* IDEA在@Autowried userMapper 處報(bào)錯(cuò),因?yàn)檎也坏阶⑷氲膶?duì)象,因?yàn)轭愂莿?dòng)態(tài)創(chuàng)建的,但是程序可以正確的執(zhí)行。
* 為了避免報(bào)錯(cuò),可以在 dao 層 的接口上添加 @Repository
*/
@Repository
public interface UserMapper extends BaseMapper<User> {
}
這里的DAO層接口直接繼承BaseMapper,類型為User,這樣,就直接可以使用MyBatis-Plus所提供的CRUD。
4.單元測(cè)試
package com.atguigu.mpdemo1010;
import com.atguigu.mpdemo1010.entity.User;
import com.atguigu.mpdemo1010.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.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.test.context.junit4.SpringRunner;
import javax.jws.soap.SOAPBinding;
import java.util.Arrays;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Mpdemo1010ApplicationTests {
@Autowired
private UserMapper userMapper;
//查詢
@Test
public void selectUser() {
List<User> users = userMapper.selectList(null);
for (User user:users){
System.out.println(user);
}
}
//添加
@Test
public void insertUser(){
User user = new User();
user.setName("岳不群");
user.setAge(56);
user.setEmail("Dava@qq.com");
userMapper.insert(user);
}
//修改
@Test
public void updateUser(){
User user = new User();
user.setId(1305766050880610306L); //因?yàn)閕d是Long類型
user.setAge(110);
userMapper.updateById(user);
}
//刪除
@Test
public void deleteUser(){
userMapper.deleteById(1305787376383143938L);
}
}
5.數(shù)據(jù)庫(kù)

二、自動(dòng)填充
當(dāng)我們?cè)诓迦牖蛐薷囊粭l數(shù)據(jù)時(shí),某種情境下,我們可能希望在插入或修改之后,能夠自動(dòng)往數(shù)據(jù)庫(kù)中填充該條記錄的創(chuàng)建或修改時(shí)間。
此時(shí)有兩種常用的方法:
1.在進(jìn)行insert或update前,手動(dòng)set記錄的創(chuàng)建或修改時(shí)間
user.setCreateTime(new Data());
user.setUpdateTime(new Data());
2.若你使用了mybatis-plus,我們就可以使用其提供的自動(dòng)填充功能。
首先,在實(shí)體類中添加相應(yīng)字段,并添加@TableField注解
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
//該注解為mybatis-plus的自動(dòng)填充(與MetaObjectHandler配合使用)
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
然后,創(chuàng)建一個(gè)handler,設(shè)置自動(dòng)填充的內(nèi)容和和填充字段
/**
* @Author su mingxin
* @Date 2020/9/15 15:03
* 該類實(shí)現(xiàn)MetaObjectHandler接口,設(shè)置createTime和updateTime的值,用于在添加或修改操作時(shí)進(jìn)行自動(dòng)填充
* 不要忘記@Component注解,將該類交給spring管理
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
//使用mybatis-plus進(jìn)行insert操作時(shí)才會(huì)起作用
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
//使用mybatis-plus進(jìn)行update操作時(shí)才會(huì)起作用
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
這樣,我們?cè)谛绿砑右粭l記錄或者修改一條記錄時(shí),就會(huì)往數(shù)據(jù)庫(kù)中自動(dòng)填充創(chuàng)建時(shí)間或修改時(shí)間。
若想自動(dòng)填充其他字段,也可這樣設(shè)置。
三、樂(lè)觀鎖
樂(lè)觀鎖我在這里就不多說(shuō)了。MyBatis-Plus也為我們提供了樂(lè)觀鎖。
1.往表中添加一個(gè)version屬性,目的是為了對(duì)記錄的修改操作進(jìn)行控制。當(dāng)多人同時(shí)對(duì)同一記錄進(jìn)行操作時(shí),若version不對(duì),則不允許修改。

2.往實(shí)體類中添加version屬性,并添加@Version注解
@Data
public class User {
/*
@TableId(type = IdType.ID_WORKER) mybatis-plus自帶的id生成策略,生成19位的值,適用于數(shù)值類型的主鍵
@TableId(type = IdType.ID_WORKER_STR) mybatis-plus自帶的id生成策略,生成19位的值,適用于字符串類型的主鍵
若是使用mybatis-plus且沒(méi)有指定主鍵生成策略,會(huì)自動(dòng)根據(jù)主鍵類型選擇生成策略
*/
private Long id;
private String name;
private Integer age;
private String email;
//該注解為mybatis-plus的自動(dòng)填充(與MetaObjectHandler配合使用)
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Version
@TableField(fill = FieldFill.INSERT)
private Integer version;//版本號(hào) 用于樂(lè)觀鎖
}
這里我使用了mybatis-plus的自動(dòng)填充,讓每次新增一條記錄時(shí),數(shù)據(jù)庫(kù)中對(duì)應(yīng)記錄的version都為1。當(dāng)然,若是不想這樣用的話,也可以在數(shù)據(jù)庫(kù)中設(shè)置該字段的默認(rèn)值。
3.新建一個(gè)配置類MyConfig,添加樂(lè)觀鎖插件
@Configuration
@MapperScan("com.atguigu.mpdemo1010.mapper")
public class MyConfig {
/**
* 樂(lè)觀鎖插件
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
4.單元測(cè)試
//測(cè)試樂(lè)觀鎖
@Test
public void testOptimisticLock(){
User user = userMapper.selectById(1305774986337775617L);
user.setAge(180);
userMapper.updateById(user);
}
四、SQL性能分析
MyBatis-Plus還提供了有關(guān)SQL性能分析插件
需要在自定義配置類MyConfig中進(jìn)行插件的添加
/**
* SQL 執(zhí)行性能分析插件
* 開(kāi)發(fā)環(huán)境使用,線上不推薦。 maxTime 指的是 sql 最大執(zhí)行時(shí)長(zhǎng)
* dev:開(kāi)發(fā)環(huán)境
* test:測(cè)試環(huán)境
* prod:生產(chǎn)環(huán)境
*/
@Bean
@Profile({"dev","test"})// 設(shè)置 dev test 環(huán)境開(kāi)啟
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(100);//ms,超過(guò)此處設(shè)置的ms則sql不執(zhí)行
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
添加該插件后,當(dāng)執(zhí)行SQL時(shí),就可以在控制臺(tái)中看見(jiàn)插件對(duì)SQL執(zhí)行的監(jiān)控
五、邏輯刪除
邏輯刪除就是將記錄從項(xiàng)目中移除不再顯示,但是數(shù)據(jù)庫(kù)中依舊保有該記錄
1.在表中添加deleted字段,用來(lái)標(biāo)記邏輯刪除狀態(tài)。

2.在實(shí)體類中添加該字段,并使用@TableLogic注解,標(biāo)記該字段為邏輯刪除的標(biāo)記。
@Data
public class User {
/*
@TableId(type = IdType.ID_WORKER) mybatis-plus自帶的id生成策略,生成19位的值,適用于數(shù)值類型的主鍵
@TableId(type = IdType.ID_WORKER_STR) mybatis-plus自帶的id生成策略,生成19位的值,適用于字符串類型的主鍵
若是使用mybatis-plus且沒(méi)有指定主鍵生成策略,會(huì)自動(dòng)根據(jù)主鍵類型選擇生成策略
*/
private Long id;
private String name;
private Integer age;
private String email;
//該注解為mybatis-plus的自動(dòng)填充(與MetaObjectHandler配合使用)
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Version
@TableField(fill = FieldFill.INSERT)
private Integer version;//版本號(hào) 用于樂(lè)觀鎖
@TableLogic
private Integer deleted;//邏輯刪除標(biāo)記
}
3.在自定義配置類中,添加邏輯刪除插件
/**
* 邏輯刪除插件
*/
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
4.單元測(cè)試
//刪除(邏輯刪除)
@Test
public void deleteUser(){
userMapper.deleteById(1305787376383143938L);
}

被邏輯刪除的記錄的deleted字段就會(huì)改變?yōu)榉悄J(rèn)值,隨后再在項(xiàng)目中進(jìn)行查詢時(shí)除非添加查詢條件外,mybatis-plus的默認(rèn)查詢語(yǔ)句是不會(huì)查詢被邏輯刪除的字段。
(這里,我在數(shù)據(jù)庫(kù)中將deleted屬性默認(rèn)值設(shè)為0)
六、mybatis-plus復(fù)雜條件查詢
//mp實(shí)現(xiàn)復(fù)雜查詢操作
@Test
public void testSelectQuery(){
//創(chuàng)建QueryWrapper對(duì)象
QueryWrapper<User> wrapper = new QueryWrapper<>();
//通過(guò)QueryWrapper設(shè)置條件
//ge,gt,le,lt
//查詢age>=30記錄
// wrapper.ge("age",30);
//eq,ne
//查詢名字不為L(zhǎng)ucy的記錄
// wrapper.ne("name","Lucy");
//between
//查詢年齡在15-30之間的記錄
// wrapper.between("age",15,30);
//like
//模糊查詢
// wrapper.like("name","J");
//orderByDesc
//根據(jù)id進(jìn)行排序(Desc降序,ASC升序)
// wrapper.orderByDesc("id");
//last
//在SQL語(yǔ)句最后拼接SQL
// wrapper.last("limit 1");
//指定要查詢的列
wrapper.select("id","name");
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
七、mybatis-plus的分頁(yè)實(shí)現(xiàn)
@Test
public void testPage(){
/*
1.創(chuàng)建page對(duì)象,傳入兩個(gè)參數(shù):當(dāng)前頁(yè) 和 每頁(yè)顯示記錄數(shù)
2.調(diào)用mp分頁(yè)查詢方法;調(diào)用mp分頁(yè)查詢過(guò)程中,底層封裝 分頁(yè)用到的所有數(shù)據(jù)都封裝到page對(duì)象里面
*/
Page<User> page = new Page<>(1,3);
userMapper.selectPage(page,null);
//通過(guò)page對(duì)象獲取分頁(yè)數(shù)據(jù)
System.out.println(page.getCurrent());//當(dāng)前頁(yè)
System.out.println("======================================");
System.out.println(page.getRecords());//每頁(yè)數(shù)據(jù)list集合
System.out.println("======================================");
System.out.println(page.getSize());//每頁(yè)顯示記錄數(shù)
System.out.println("======================================");
System.out.println(page.getTotal());//總記錄數(shù)
System.out.println("======================================");
System.out.println(page.getPages());//總頁(yè)數(shù)
System.out.println(page.hasNext());//表示是否有下一頁(yè)
System.out.println(page.hasPrevious());//表示是否有上一頁(yè)
}
八、自動(dòng)生成代碼
自動(dòng)生成代碼的教程可以參考官方介紹
這里我轉(zhuǎn)載了其他大哥的技術(shù)博客,以供學(xué)習(xí),感謝分享