Mybatis-Plus
-
- 一、特性
- 二、使用步驟
-
- 1、建立資料庫 mybatis_plus,建立表
- 2、建立SpringBoot項目!
- 3、導入依賴
- 4、配置
- 5、建實體類
- 6、mapper接口
- 7、入口類掃描dao
- 三、配置日志
- 四、CRUD擴充
-
- 1、插入操作
- 2、主鍵生成政策
- 3、更新操作
- 4、自動填充
-
- 1. 方式一:資料庫級别(工作中不允許你修改資料庫)
- 2. 方式二:代碼級别
- 5、樂觀鎖
-
- 測試一下MP的樂觀鎖插件
- 6、查詢操作
- 7、分頁查詢
- 8、删除操作
- 9、邏輯删除
- 10、性能分析插件
- 11、條件構造器
- 12、代碼自動生成器
感謝B站up主【狂神說Java】原文,有學習的夥伴可以看這位up主!
一、特性
- 無侵入:隻做增強不做改變,引入它不會對現有工程産生影響,如絲般順滑
- 損耗小:啟動即會自動注入基本 CURD,性能基本無損耗,直接面向對象操作, BaseMapper
- 強大的 CRUD 操作:内置通用 Mapper、通用 Service,僅僅通過少量配置即可實作單表大部分
- CRUD 操作,更有強大的條件構造器,滿足各類使用需求, 以後簡單的CRUD操作,它不用自己編寫 了!
- 支援 Lambda 形式調用:通過 Lambda 表達式,友善的編寫各類查詢條件,無需再擔心字段寫錯
- 支援主鍵自動生成:支援多達 4 種主鍵政策(内含分布式唯一 ID 生成器 - Sequence),可自由配 置,完美解決主鍵問題
-
支援 ActiveRecord 模式:支援 ActiveRecord 形式調用,實體類隻需繼承 Model 類即可進行強大 的 CRUD
操作
- 支援自定義全局通用操作:支援全局通用方法注入( Write once, use anywhere )
-
内置代碼生成器:采用代碼或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller
層代碼,支援模闆引擎,更有超多自定義配置等您來使用(自動幫你生成代碼)
- 内置分頁插件:基于 MyBatis 實體分頁,開發者無需關心具體操作,配置好插件之後,寫分頁等同 于普通 List 查詢
-
分頁插件支援多種資料庫:支援 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、
Postgre、SQLServer 等多種資料庫
- 内置性能分析插件:可輸出 Sql 語句以及其執行時間,建議開發測試時啟用該功能,能快速揪出慢 查詢
- 内置全局攔截插件:提供全表 delete 、 update 操作智能分析阻斷,也可自定義攔截規則,預防誤 操作
二、使用步驟
1、建立資料庫 mybatis_plus,建立表
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, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
-- 真實開發中,version(樂觀鎖)、deleted(邏輯删除)、gmt_create、gmt_modified
2、建立SpringBoot項目!
3、導入依賴
<!-- 資料庫驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus -->
<!-- mybatis-plus 是自己開發,并非官方的! -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
4、配置
# mysql 5 驅動不同 com.mysql.jdbc.Driver
# mysql 8 驅動不同com.mysql.cj.jdbc.Driver、需要增加時區的配置
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、建實體類
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
6、mapper接口
// 在對應的Mapper上面繼承基本的類 BaseMapper
@Repository // 代表持久層
public interface UserMapper extends BaseMapper<User> {
// 所有的CRUD操作都已經編寫完成了
// 你不需要像以前的配置一大堆檔案了!
}
7、入口類掃描dao
在主啟動類上去掃描我們的mapper包下的所有接口
三、配置日志
我們所有的sql現在是不可見的,我們希望知道它是怎麼執行的,是以我們必須要看日志!
# 配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

配置完畢日志之後,後面的學習就需要注意這個自動生成的SQL,你們就會喜歡上 MyBatis-Plus!
四、CRUD擴充
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);//幫我們自動生成id
System.out.println(result);// 受影響的行數
System.out.println(user);// 發現id會自動回填
}
2、主鍵生成政策
在實體類字段上 @TableId(type = IdType.xxx),一共有六種主鍵生成政策
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
/*
@TableId(type = IdType.ASSIGN_ID) // 1. 生成一個19位随機值
@TableId(type = IdType.ASSIGN_UUIE) // 2. 生成一個uuid
@TableId(type = IdType.AUTO) // 3.資料庫id自增 注意:在資料庫裡字段一定要設定自增!
@TableId(type = IdType.NONE) // 4.未設定主鍵 要自己set
@TableId(type = IdType.INPUT) // 5.手動輸入 要自己set
@TableId(type = IdType.ID_WORKER) // 預設的全局唯一id 新版過時
@TableId(type = IdType.UUID) // 全局唯一id uuid 新版過時
@TableId(type = IdType.ID_WORKER_STR) // 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、自動填充
建立時間、修改時間!這些個操作一遍都是自動化完成的,我們不希望手動更新!
阿裡巴巴開發手冊:所有的資料庫表:gmt_create、gmt_modified幾乎所有的表都要配置上!而且需要自動化!
1. 方式一:資料庫級别(工作中不允許你修改資料庫)
在表中新增字段 create_time, update_time,
實體類同步
private Date createTime;
private Date updateTime;
以下為操作後的變化
2. 方式二:代碼級别
1、删除資料庫的預設值、更新操作!
2、實體類字段屬性上需要增加注解
// 字段添加填充内容
@TableField(fill = FieldFill.INSERT)//插入的時候操作
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)//插入和更新的時候都操作
private Date updateTime
3、編寫處理器來處理這個注解即可!
@Slf4j
@Component//加入spring容器
public class MuMetaObjecHandler implements MetaObjectHandler {
// 插入時的填充政策
@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);
}
// 更新時的填充政策
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill.....");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
4、測試插入、更新後觀察時間!
5、樂觀鎖
樂觀鎖 : 故名思意十分樂觀,它總是認為不會出現問題,無論幹什麼不去上鎖!如果出現了問題,再次更新值測試,給所有的記錄加一個version
悲觀鎖:故名思意十分悲觀,它總是認為總是出現問題,無論幹什麼都會上鎖!再去操作!
樂觀鎖實作方式:
- 取出記錄時,擷取目前 version
- 更新時,帶上這個version
- 執行更新時, set version = newVersion where version = oldVersion
- 如果version不對,就更新失敗
樂觀鎖:1、先查詢,獲得版本号 version = 1
-- A 線程
update user set name = "kuangshen", version = version + 1
where id = 2 and version = 1
-- B 線程搶先完成,這個時候 version = 2,會導緻 A 修改失敗!
update user set name = "kuangshen", version = version + 1
where id = 2 and version = 1
測試一下MP的樂觀鎖插件
1、給資料庫中增加version字段!
2、實體類加對應的字段
@Version //樂觀鎖Version注解
private Integer version;
3、注冊元件
// 掃描的 mapper 檔案夾
@MapperScan("com.yn.mapper")
@EnableTransactionManagement
@Configuration // 配置類
public class MyBatisPlusConfig {
// 注冊樂觀鎖插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
3、測試
// 測試樂觀鎖成功!
@Test
public void testOptimisticLocker() {
// 1、查詢使用者資訊
User user = userMapper.selectById(1L);
// 2、修改使用者資訊
user.setName("kuangshen");
user.setEmail("[email protected]");
// 3、執行更新操作
userMapper.updateById(user);
}
// 測試樂觀鎖失敗!多線程下
@Test
public void testOptimisticLocker2() {
// 線程 1
User user = userMapper.selectById(1L);
user.setName("kuangshen111");
user.setEmail("[email protected]");
// 模拟另外一個線程執行了插隊操作
User user2 = userMapper.selectById(1L);
user2.setName("kuangshen222");
user2.setEmail("[email protected]");
userMapper.updateById(user2);
// 自旋鎖來多次嘗試送出!
userMapper.updateById(user); // 如果沒有樂觀鎖就會覆寫插隊線程的值!
}
6、查詢操作
// 測試查詢
@Test
public void testSelectById() {
User user = userMapper.selectById(1L);
System.out.println(user);
}
// 測試批量查詢!
@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 {
// 注冊樂觀鎖插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
//分頁插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
2.直接使用Page對象即可
// 測試分頁查詢
@Test
public void testPage() {
// 參數一:目前頁
// 參數二:頁面大小
// 使用了分頁插件之後,所有的分頁操作也變得簡單的!
Page<User> page = new Page<>(2, 3);
userMapper.selectPage(page, null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());
}
8、删除操作
// 測試删除
@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、邏輯删除
實體删除 :從資料庫中直接移除
邏輯删除 :再資料庫中沒有被移除,而是通過一個變量來讓他失效! deleted = 0 => deleted = 1
管理者可以檢視被删除的記錄!防止資料的丢失,類似于資源回收筒!
邏輯删除步驟:
1、在資料表中增加一個 deleted 字段
2、實體類中增加屬性
@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、性能分析插件
我們在平時的開發中,會遇到一些慢sql。
作用:性能分析攔截器,用于輸出每條 SQL 語句及其執行時間
MP也提供性能分析插件,如果超過這個時間就停止運作!
1、導入插件
/**
* * SQL執行效率插件
*
*/
@Bean
@Profile({"dev", "test"})// 設定 dev test 環境開啟,保證我們的效率
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(100); // ms設定sql執行的最大時間,如果超過了則不執行
performanceInterceptor.setFormat(true); // 是否格式化代碼
return performanceInterceptor;
}
記住,要在SpringBoot中配置環境為dev或者 test 環境!
#設定開發環境
spring.profiles.active=dev
2、測試使用!
@Test
void contextLoads() {
// 參數是一個 Wrapper ,條件構造器,這裡我們先不用 null
// 查詢全部使用者
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
11、條件構造器
我們寫一些複雜的sql就可以使用它來替代!
@SpringBootTest
public class WrapperTest {
@Autowired
private UserMapper userMapper;
//1、測試一,記住檢視輸出的SQL進行分析
@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); // 和我們剛才學習的map對比一下
}
//2、測試二
@Test
void test2() {
// 查詢名字狂神說
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "狂神說");
User user = userMapper.selectOne(wrapper); // 查詢一個資料,出現多個結果使用List或者 Map
System.out.println(user);
}
//3、區間查詢
@Test
void test3() {
// 查詢年齡在 20 ~ 30 歲之間的使用者
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age", 20, 30); // 區間
Integer count = userMapper.selectCount(wrapper);// 查詢結果數
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進行排序
wrapper.orderByDesc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
}
12、代碼自動生成器
AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成Entity、Mapper、Mapper XML、Service、Controller 等各個子產品的代碼,極大的提升了開發效率。
測試:
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) {
// 需要建構一個 代碼自動生成器 對象
AutoGenerator mpg = new AutoGenerator();
// 配置政策
// 1、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");//擷取目前的項目路徑
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);//自動配置Swagger文檔
mpg.setGlobalConfig(gc);
//2、設定資料源
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");//放在哪個包下
pc.setEntity("entity");//實體類的包名字
pc.setMapper("mapper");//dao的包字
pc.setService("service");//server的包名
pc.setController("controller");//controller的包名
mpg.setPackageInfo(pc);
//4、政策配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user"); // 設定要映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);//資料庫表名 下劃線轉駝峰命名
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//資料庫列的名字 下劃線轉駝峰命名
strategy.setEntityLombokModel(true); // 自動生成 lombok;
strategy.setLogicDeleteFieldName("deleted");//邏輯删除
// 自動填充配置
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中連結請求:localhost:8080/hello_id_2
mpg.setStrategy(strategy);
mpg.execute(); //執行
}
}
報錯的可以導一下這個包
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>