MyBatis-Plus簡單上手教程(案例)(IDEA+SpringBoot+Maven+Mybatis-Plus)
一、簡單開始
1、簡介
MyBatis-Plus 是一個 Mybatis 增強(qiáng)版工具,在 MyBatis 上擴(kuò)充了其他功能,并沒有改變Mybatis的基本功能,為了簡化開發(fā)提交效率而存在。
官網(wǎng)文檔地址:
https://mp.baomidou.com/guide/
MyBatis-Plus 特性:
https://mp.baomidou.com/guide/#%E7%89%B9%E6%80%A7
2、使用
(1)準(zhǔn)備工作
使用IDEA創(chuàng)建一個SpringBoot+Maven項目。
(3)添加 MyBatis-Plus 依賴(mybatis-plus-boot-starter)
<dependency>
? ?<groupId>com.baomidou</groupId>
? ?<artifactId>mybatis-plus-boot-starter</artifactId>
? ?<version>3.3.1.tmp</version></dependency>
1
2
3
4
5
(4)添加MySQL、Lombok依賴
<!-- ? ? ? ?mysql依賴--><dependency>
? ?<groupId>mysql</groupId>
? ?<artifactId>mysql-connector-java</artifactId>
? ?<version>8.0.18</version></dependency><!-- ? ? ? ?Lombok--><dependency>
? ?<groupId>org.projectlombok</groupId>
? ?<artifactId>lombok</artifactId>
? ?<version>1.18.10</version></dependency>
1
2
3
4
5
6
7
8
9
10
11
12
(5)完整依賴文件(pom.xml)
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
? ? ? ? xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
? ?<modelVersion>4.0.0</modelVersion>
? ?<parent>
? ? ? ?<groupId>org.springframework.boot</groupId>
? ? ? ?<artifactId>spring-boot-starter-parent</artifactId>
? ? ? ?<version>2.2.11.RELEASE</version>
? ? ? ?<relativePath/> <!-- lookup parent from repository -->
? ?</parent>
? ?<groupId>com.cncc</groupId>
? ?<artifactId>test_mybatis_plus2</artifactId>
? ?<version>0.0.1-SNAPSHOT</version>
? ?<name>test_mybatis_plus2</name>
? ?<description>Demo project for Spring Boot</description>
? ?<properties>
? ? ? ?<java.version>1.8</java.version>
? ?</properties>
? ?<dependencies>
? ? ? ?<!-- ? ? ? ?mybatisplus依賴-->
? ? ? ?<dependency>
? ? ? ? ? ?<groupId>com.baomidou</groupId>
? ? ? ? ? ?<artifactId>mybatis-plus-boot-starter</artifactId>
? ? ? ? ? ?<version>3.3.1.tmp</version>
? ? ? ?</dependency>
? ? ? ?<!--代碼生成器-->
? ? ? ?<dependency>
? ? ? ? ? ?<groupId>com.baomidou</groupId>
? ? ? ? ? ?<artifactId>mybatis-plus-generator</artifactId>
? ? ? ? ? ?<version>3.3.1.tmp</version>
? ? ? ?</dependency>
? ? ? ?<!-- ? ? ? ?模板引擎依賴-->
? ? ? ?<dependency>
? ? ? ? ? ?<groupId>org.apache.velocity</groupId>
? ? ? ? ? ?<artifactId>velocity</artifactId>
? ? ? ? ? ?<version>1.7</version>
? ? ? ?</dependency>
? ? ? ?<!-- ? ? ? ?mysql依賴-->
? ? ? ?<dependency>
? ? ? ? ? ?<groupId>mysql</groupId>
? ? ? ? ? ?<artifactId>mysql-connector-java</artifactId>
? ? ? ? ? ?<version>8.0.18</version>
? ? ? ?</dependency>
? ? ? ?<!-- ? ? ? ?Lombok-->
? ? ? ?<dependency>
? ? ? ? ? ?<groupId>org.projectlombok</groupId>
? ? ? ? ? ?<artifactId>lombok</artifactId>
? ? ? ? ? ?<version>1.18.10</version>
? ? ? ?</dependency>
? ? ? ?<dependency>
? ? ? ? ? ?<groupId>org.springframework.boot</groupId>
? ? ? ? ? ?<artifactId>spring-boot-starter</artifactId>
? ? ? ?</dependency>
? ? ? ?<dependency>
? ? ? ? ? ?<groupId>org.springframework.boot</groupId>
? ? ? ? ? ?<artifactId>spring-boot-starter-test</artifactId>
? ? ? ? ? ?<scope>test</scope>
? ? ? ? ? ?<exclusions>
? ? ? ? ? ? ? ?<exclusion>
? ? ? ? ? ? ? ? ? ?<groupId>org.junit.vintage</groupId>
? ? ? ? ? ? ? ? ? ?<artifactId>junit-vintage-engine</artifactId>
? ? ? ? ? ? ? ?</exclusion>
? ? ? ? ? ?</exclusions>
? ? ? ?</dependency>
? ? ? ?<dependency>
? ? ? ? ? ?<groupId>junit</groupId>
? ? ? ? ? ?<artifactId>junit</artifactId>
? ? ? ?</dependency>
? ? ? ?<dependency>
? ? ? ? ? ?<groupId>org.springframework.boot</groupId>
? ? ? ? ? ?<artifactId>spring-boot-starter-web</artifactId>
? ? ? ?</dependency>
? ?</dependencies>
? ?<build>
? ? ? ?<plugins>
? ? ? ? ? ?<plugin>
? ? ? ? ? ? ? ?<groupId>org.springframework.boot</groupId>
? ? ? ? ? ? ? ?<artifactId>spring-boot-maven-plugin</artifactId>
? ? ? ? ? ?</plugin>
? ? ? ?</plugins>
? ? ? ?<!--配置資源-->
? ? ? ?<resources>
? ? ? ? ? ?<resource>
? ? ? ? ? ? ? ?<directory>src/main/java</directory>
? ? ? ? ? ? ? ?<includes>
? ? ? ? ? ? ? ? ? ?<include>**/*.xml</include>
? ? ? ? ? ? ? ?</includes>
? ? ? ? ? ?</resource>
? ? ? ? ? ?<resource>
? ? ? ? ? ? ? ?<directory>src/main/resources</directory>
? ? ? ? ? ?</resource>
? ? ? ?</resources>
? ?</build></project>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
(6)在數(shù)據(jù)庫中創(chuàng)建一個表
我建了一個t_user表,字段為id,name,password。
(7)在 application.yml 文件中配置 mysql 數(shù)據(jù)源信息。
spring:
?datasource:
? ?driver-class-name: com.mysql.cj.jdbc.Driver ? ?username: root ? ?password: 123456
? ?url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
1
2
3
4
5
6

(8)對于entity、mapper,service,controller的創(chuàng)建有兩種方式。一種為自己手動創(chuàng)建,另一種為使用Mybatis-Plus代碼生成器自動生成。
自己手動創(chuàng)建:
編寫表對應(yīng)的 實(shí)體類。
package entity;import lombok.Data;@Datapublic class User {
? ?private Long id;
? ?private String name;
? ?private String password;}
1
2
3
4
5
6
7
8
9
10

編寫操作實(shí)體類的 Mapper 類。需繼承 BaseMapper,這是 mybatis-plus 封裝好的類。
package com.cncc.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.cncc.entity.User;public interface UserMapper extends BaseMapper<User> {}
1
2
3
4
5
6
7
8

手動創(chuàng)建就到這里。service和controller暫時省略。因為實(shí)體類、Mapper 類都寫好后就可以使用了。
(使用參考(9))
代碼生成器創(chuàng)建:
添加依賴
<!--代碼生成器-->
? ? ? ?<dependency>
? ? ? ? ? ?<groupId>com.baomidou</groupId>
? ? ? ? ? ?<artifactId>mybatis-plus-generator</artifactId>
? ? ? ? ? ?<version>3.3.1.tmp</version>
? ? ? ?</dependency>
? ? ? ?<!-- ? ? ? ?模板引擎依賴-->
? ? ? ?<dependency>
? ? ? ? ? ?<groupId>org.apache.velocity</groupId>
? ? ? ? ? ?<artifactId>velocity</artifactId>
? ? ? ? ? ?<version>1.7</version>
? ? ? ?</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
新建一個測試類

(注意import的類,別導(dǎo)錯了)
package com.cncc.autogenerator;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.rules.DateType;import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;import org.junit.Test;public class TestAutoGenerate {
? ?@Test
? ?public ?void autoGenerate(){
? ? ? ?//步驟1:創(chuàng)建代碼生成器,用于代碼生成。
? ? ? ?AutoGenerator autoGenerator = new AutoGenerator();
? ? ? ?//步驟2: 全局配置。指定代碼輸出路徑以及包名、作者等信息。
? ? ? ?GlobalConfig globalConfig = new GlobalConfig();
? ? ? ?// 填寫代碼生成的目錄(自己項目所在目錄)
? ? ? ?String projectPath = "D:\\WorkSpace\\IDEA_CNCC\\test_mybatis_plus2";
? ? ? ?// 拼接出代碼最終輸出的目錄
? ? ? ?globalConfig.setOutputDir(projectPath+"/src/main/java");
? ? ? ?// 配置開發(fā)者信息(可選)(需要修改)
? ? ? ?globalConfig.setAuthor("zyk");
? ? ? ?// 配置是否打開目錄,false 為不打開(可選)
? ? ? ?globalConfig.setOpen(false);
? ? ? ?// 實(shí)體屬性 Swagger2 注解,添加 Swagger 依賴,開啟 Swagger2 模式(可選)
? ? ? ?//globalConfig.setSwagger2(true);
? ? ? ?// 重新生成文件時是否覆蓋,false 表示不覆蓋(可選)
? ? ? ?globalConfig.setFileOverride(false);
? ? ? ?// 配置主鍵生成策略,此處為 ASSIGN_ID(可選)
? ? ? ?globalConfig.setIdType(IdType.ASSIGN_ID);
? ? ? ?// 配置日期類型,此處為 ONLY_DATE(可選)
? ? ? ?globalConfig.setDateType(DateType.ONLY_DATE);
? ? ? ?// 默認(rèn)生成的 service 會有 I 前綴
? ? ? ?globalConfig.setServiceName("%sService");
? ? ? ?autoGenerator.setGlobalConfig(globalConfig);
? ? ? ?// 步驟3:數(shù)據(jù)源配置。(需要修改) ?用于指定需要生成代碼的數(shù)據(jù)倉庫,數(shù)據(jù)表。
? ? ? ?DataSourceConfig dsc = new DataSourceConfig();
? ? ? ?// 配置數(shù)據(jù)庫 url 地址
? ? ? ?dsc.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC");
? ? ? ?// dsc.setSchemaName("testMyBatisPlus"); // 可以直接在 url 中指定數(shù)據(jù)庫名
? ? ? ?// 配置數(shù)據(jù)庫驅(qū)動
? ? ? ?dsc.setDriverName("com.mysql.cj.jdbc.Driver");
? ? ? ?// 配置數(shù)據(jù)庫連接用戶名
? ? ? ?dsc.setUsername("root");
? ? ? ?// 配置數(shù)據(jù)庫連接密碼
? ? ? ?dsc.setPassword("123456");
? ? ? ?autoGenerator.setDataSource(dsc);
? ? ? ?// 步驟:4:包配置 ?配置包信息
? ? ? ?PackageConfig packageConfig = new PackageConfig();
? ? ? ?// 配置父包名(需要修改)
? ? ? ?packageConfig.setParent("com.cncc");
? ? ? ?// 配置模塊名(需要修改) ?(這里是設(shè)置com.cncc的下一級,如果為空,則創(chuàng)建的包會直接在com.cncc下;如果不為空,例如填為test,則創(chuàng)建的包會在com.cncc.test下.)
? ? ? ?packageConfig.setModuleName("");
? ? ? ?// 配置 entity 包名
? ? ? ?packageConfig.setEntity("entity");
? ? ? ?// 配置 mapper 包名
? ? ? ?packageConfig.setMapper("mapper");
? ? ? ?// 配置 service 包名
? ? ? ?packageConfig.setService("service");
? ? ? ?// 配置 controller 包名
? ? ? ?packageConfig.setController("controller");
? ? ? ?autoGenerator.setPackageInfo(packageConfig);
? ? ? ?// 步驟5:策略配置(數(shù)據(jù)庫表配置)
? ? ? ?StrategyConfig strategy = new StrategyConfig();
? ? ? ?// 指定表名(可以同時操作多個表,使用 , 隔開)(需要修改)
? ? ? ?strategy.setInclude("t_user");
? ? ? ?// 配置數(shù)據(jù)表與實(shí)體類名之間映射的策略
? ? ? ?strategy.setNaming(NamingStrategy.underline_to_camel);
? ? ? ?// 配置數(shù)據(jù)表的字段與實(shí)體類的屬性名之間映射的策略
? ? ? ?strategy.setColumnNaming(NamingStrategy.underline_to_camel);
? ? ? ?// 配置 lombok 模式
? ? ? ?strategy.setEntityLombokModel(true);
? ? ? ?// 配置 rest 風(fēng)格的控制器(@RestController)
? ? ? ?strategy.setRestControllerStyle(true);
? ? ? ?// 配置駝峰轉(zhuǎn)連字符
? ? ? ?strategy.setControllerMappingHyphenStyle(true);
? ? ? ?// 配置表前綴,生成實(shí)體時去除表前綴
? ? ? ?// 此處的表名為 test_mybatis_plus_user,模塊名為 test_mybatis_plus,去除前綴后剩下為 user。
? ? ? ?strategy.setTablePrefix(packageConfig.getModuleName() + "_");
? ? ? ?autoGenerator.setStrategy(strategy);
? ? ? ?// Step6:執(zhí)行代碼生成操作
? ? ? ?autoGenerator.execute();
? ?}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
運(yùn)行測試方法后:

(9)實(shí)體類、Mapper 類都寫好了,就可以使用了。
Step1:先得在啟動類里掃描 Mapper 類,即添加 @MapperScan 注解
package com.cncc;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@MapperScan("com.cncc.mapper")public class TestMybatisPlusApplication {
? ?public static void main(String[] args) {
? ? ? ?SpringApplication.run(TestMybatisPlusApplication.class, args);
? ?}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Step2:在測試類里寫一個測試方法測試一下。

? ?@Autowired
? ?private UserMapper userMapper;
? ?@Test
? ?public void testSelect() {
? ? ? ?System.out.println(("----- selectAll method test ------"));
? ? ? ?List<User> userList = userMapper.selectList(null);
? ? ? ?for(User user:userList) {
? ? ? ? ? ?System.out.println(user);
? ? ? ?}
? ?}
1
2
3
4
5
6
7
8
9
10
11
(10)總結(jié):
通過以上簡單操作,就能對 user 表進(jìn)行 CRUD 操作,不需要去編寫 xml 文件。
注:
若遇到報錯mapper文件掃描不到,在pom.xml文件里添加如下代碼:

<resources>
? ? ? ? ? ?<resource>
? ? ? ? ? ? ? ?<directory>src/main/java</directory>
? ? ? ? ? ? ? ?<includes>
? ? ? ? ? ? ? ? ? ?<include>**/*.xml</include>
? ? ? ? ? ? ? ?</includes>
? ? ? ? ? ?</resource>
? ? ? ? ? ?<resource>
? ? ? ? ? ? ? ?<directory>src/main/resources</directory>
? ? ? ? ? ?</resource>
? ? ? ?</resources>
1
2
3
4
5
6
7
8
9
10
11
二、Mybatis-Plus 常用操作
1、配置日志
想要查看執(zhí)行的 sql 語句,可以在 yml 文件中添加配置信息,如下。
mybatis-plus:
?configuration:
? ?log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
1
2
3

2、自動填充數(shù)據(jù)功能
(1)添加、修改數(shù)據(jù)時,每次都會使用相同的方式進(jìn)行填充。比如 數(shù)據(jù)的創(chuàng)建時間、修改時間等。
Mybatis-plus 支持自動填充這些字段的數(shù)據(jù)。
給之前的數(shù)據(jù)表新增兩個字段:創(chuàng)建時間create_time、修改時間update_time。
并使用 代碼生成器生成代碼。
(3)使用自動填充功能。
Step1:
在實(shí)體類里使用 @TableField 注解標(biāo)注需要進(jìn)行填充的字段。
/**
* 創(chuàng)建時間
*/
@TableField(fill = FieldFill.INSERT)
private Date createTime;
/**
* 最后修改時間
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
1
2
3
4
5
6
7
8
9
10
11
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-gpYh5O2W-1606980063900)(C:\Users\KK\AppData\Roaming\Typora\typora-user-images\1606908908847.png)]

Step2:
自定義一個類,實(shí)現(xiàn) MetaObjectHandler 接口,并重寫方法。
添加 @Component 注解,交給 Spring 去管理。
package com.cncc.handler;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;import org.apache.ibatis.reflection.MetaObject;import org.springframework.stereotype.Component;import java.util.Date;@Componentpublic class MyMetaObjectHandler implements MetaObjectHandler {
? ?@Override
? ?public void insertFill(MetaObject metaObject) {
? ? //createTime、updateTime為屬性名
? ? ? ?this.strictInsertFill(metaObject,"createTime", Date.class,new Date());
? ? ? ?this.strictInsertFill(metaObject,"updateTime", Date.class,new Date());
? ?}
? ?@Override
? ?public void updateFill(MetaObject metaObject) {
? ? ? ?this.strictUpdateFill(metaObject,"updateTime",Date.class,new Date());
? ?}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Step3:
簡單測試一下。
? ?@Test
? ?void testInsert2(){//自動填充數(shù)據(jù)測試 ?這里自動填充了創(chuàng)建時間和最后修改時間
? ? ? ?TUser uer = new TUser();
? ? ? ?uer.setName("ZiDong3").setPassword("2222222");
? ? ? ?if (userService.save(uer)){
? ? ? ? ? ?for (TUser user : userService.list()) {
? ? ? ? ? ? ? ?System.out.println(user);
? ? ? ? ? ?}
? ? ? ?}else {
? ? ? ? ? ?System.out.println("添加數(shù)據(jù)失?。?#34;);
? ? ? ?}
? ?}
1
2
3
4
5
6
7
8
9
10
11
12
13
3、邏輯刪除
(1)簡介
刪除數(shù)據(jù),可以通過物理刪除,也可以通過邏輯刪除。
物理刪除指的是直接將數(shù)據(jù)從數(shù)據(jù)庫中刪除,不保留。
邏輯刪除指的是修改數(shù)據(jù)的某個字段,使其表示為已刪除狀態(tài),而非刪除數(shù)據(jù),保留該數(shù)據(jù)在數(shù)據(jù)庫中,但是查詢時不顯示該數(shù)據(jù)(查詢時過濾掉該數(shù)據(jù))。
給數(shù)據(jù)表增加一個字段:delete_flag,用于表示該數(shù)據(jù)是否被邏輯刪除。
(2)使用邏輯刪除。
可以定義一個自動填充規(guī)則,初始值為 0。0 表示未刪除, 1 表示刪除。
//在實(shí)體類里添加屬性/**
* 邏輯刪除(0 未刪除、1 刪除)
*/@TableLogic(value = "0", delval = "1")@TableField(fill = FieldFill.INSERT)private Integer deleteFlag;//在自定義的實(shí)現(xiàn)MetaObjectHandler接口的類里 @Overridepublic void insertFill(MetaObject metaObject) {
? ?this.strictInsertFill(metaObject, "deleteFlag", Integer.class, 0);}
1
2
3
4
5
6
7
8
9
10
11
12
13
14


(3)簡單測試
使用 mybatis-plus 封裝好的方法時,會自動添加邏輯刪除的功能。
若是自定義的 sql 語句,需要手動添加邏輯。
//邏輯刪除
? ?/*
? ? ? ?物理刪除指的是直接將數(shù)據(jù)從數(shù)據(jù)庫中刪除,不保留。
邏輯刪除指的是修改數(shù)據(jù)的某個字段,使其表示為已刪除狀態(tài),
? ?而非刪除數(shù)據(jù),保留該數(shù)據(jù)在數(shù)據(jù)庫中,但是查詢時不顯示該
? ?數(shù)據(jù)(查詢時過濾掉該數(shù)據(jù))。
? ? */
? ?//可以定義一個自動填充規(guī)則,初始值為 0。0 表示未刪除, 1 表示刪除。
? ?//注意:當(dāng)使用邏輯刪除這個功能后,若提供判斷的屬性值不為0(假設(shè)設(shè)置0表示未刪除),則查不到。
? ?@Test
? ?public void testDelete() {
? ? ? ?if (userService.removeById(12)) {
? ? ? ? ? ?System.out.println("刪除數(shù)據(jù)成功");
? ? ? ? ? ?userService.list().forEach(System.out::println);
? ? ? ?} else {
? ? ? ? ? ?System.out.println("刪除數(shù)據(jù)失敗");
? ? ? ?}
? ?}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
現(xiàn)有數(shù)據(jù) 為:

執(zhí)行 testDelete 進(jìn)行邏輯刪除后:

PS:若去除屬性上的 TableLogic 注解,則再執(zhí)行 testDelete 時會進(jìn)行物理刪除,直接刪除這條數(shù)據(jù)。
4、分頁插件的使用
Step1:
配置分頁插件。
編寫一個 配置類,內(nèi)部使用 @Bean 注解將 PaginationInterceptor 交給 Spring 容器管理。
package com.cncc.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
//@MapperScan("com.cncc.mapper")
public class Myconfig {
? ?/**
? ? * 分頁插件
? ? * @return 分頁插件的實(shí)例
? ? */
? ?@Bean
? ?public PaginationInterceptor paginationInterceptor() {
? ? ? ?return new PaginationInterceptor();
? ?}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Step2:
編寫分頁代碼。
直接 new 一個 Page 對象,對象需要傳遞兩個參數(shù)(當(dāng)前頁,每頁顯示的條數(shù))。
調(diào)用 mybatis-plus 提供的分頁查詢方法,其會將 分頁查詢的數(shù)據(jù)封裝到 Page 對象中。
//分頁查詢
? ?/*
? ?直接 new 一個 Page 對象,對象需要傳遞兩個參數(shù)(當(dāng)前頁,每頁顯示的條數(shù))。
調(diào)用 mybatis-plus 提供的分頁查詢方法,其會將 分頁查詢的數(shù)據(jù)封裝到 Page 對象中。
? ? */
? ?@Test
? ?public void testPage() {
? ? ? ?// Step1:創(chuàng)建一個 Page 對象
? ? ? // Page<TUser> page = new Page<>();//默認(rèn)當(dāng)前頁為第一頁,每頁大小為10
? ? ? ? Page<TUser> page = new Page<>(2, 5);//設(shè)置當(dāng)前頁為第二頁,每頁5條數(shù)據(jù)
? ? ? ?// Step2:調(diào)用 mybatis-plus 提供的分頁查詢方法
? ? ? ?userService.page(page, null);
? ? ? ?// Step3:獲取分頁數(shù)據(jù)
? ? ? ?System.out.println(page.getCurrent()); // 獲取當(dāng)前頁
? ? ? ?System.out.println(page.getTotal()); // 獲取總記錄數(shù)
? ? ? ?System.out.println(page.getSize()); // 獲取每頁的條數(shù)
? ? ? ?System.out.println(page.getRecords()); // 獲取每頁數(shù)據(jù)的集合
? ? ? ?System.out.println(page.getPages()); // 獲取總頁數(shù)
? ? ? ?System.out.println(page.hasNext()); // 是否存在下一頁
? ? ? ?System.out.println(page.hasPrevious()); // 是否存在上一頁
? ?}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-MwFazeXf-1606980063914)(C:\Users\KK\AppData\Roaming\Typora\typora-user-images\1606976358353.png)]

5、樂觀鎖(待補(bǔ)充)
三、Mybatis-Plus CRUD 操作了解
1、Mapper 接口方法(CRUD)
使用代碼生成器生成的 mapper 接口中,其繼承了 BaseMapper 接口。而 BaseMapper 接口中封裝了一系列 CRUD 常用操作(當(dāng)然,自定義代碼執(zhí)行也可以),可以直接使用。
此處簡單介紹一下 BaseMapper 接口中的常用方法:
添加數(shù)據(jù):
方法介紹int insert(T entity);// 插入一條記錄
注:
? ?T ? ? ? ? 表示任意實(shí)體類型
? ?entity ? ?表示實(shí)體對象
1
2
3
刪除數(shù)據(jù):
方法介紹int deleteById(Serializable id);// 根據(jù)主鍵 ID 刪除int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);// 根據(jù) map 定義字段的條件刪除int delete(@Param(Constants.WRAPPER) Wrapper wrapper);// 根據(jù)實(shí)體類定義的 條件刪除對象int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);// 進(jìn)行批量刪除
注:
? ?id ? ? ? ?表示 主鍵 ID
? ?columnMap 表示表字段的 map 對象
? ?wrapper ? 表示實(shí)體對象封裝操作類,可以為 null。
? ?idList ? ?表示 主鍵 ID 集合(列表、數(shù)組),不能為 null 或 empty
1
2
3
4
5
修改數(shù)據(jù):
方法介紹int updateById(@Param(Constants.ENTITY) T entity);// 根據(jù) ID 修改實(shí)體對象。int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper updateWrapper);// 根據(jù) updateWrapper 條件修改實(shí)體對象
注:
? ?update 中的 entity 為 set 條件,可以為 null。
? ?updateWrapper 表示實(shí)體對象封裝操作類(可以為 null,里面的 entity 用于生成 where 語句)
1
2
3
查詢數(shù)據(jù):
方法介紹T selectById(Serializable id);// 根據(jù) 主鍵 ID 查詢數(shù)據(jù)List selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);// 進(jìn)行批量查詢List selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);// 根據(jù)表字段條件查詢T selectOne(@Param(Constants.WRAPPER) Wrapper queryWrapper);// 根據(jù)實(shí)體類封裝對象 查詢一條記錄Integer selectCount(@Param(Constants.WRAPPER) Wrapper queryWrapper);// 查詢記錄的總條數(shù)List selectList(@Param(Constants.WRAPPER) Wrapper queryWrapper);// 查詢所有記錄(返回 entity 集合)List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper queryWrapper);// 查詢所有記錄(返回 map 集合)List selectObjs(@Param(Constants.WRAPPER) Wrapper queryWrapper);// 查詢所有記錄(但只保存第一個字段的值)<E extends IPage> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper queryWrapper);// 查詢所有記錄(返回 entity 集合),分頁<E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper queryWrapper);// 查詢所有記錄(返回 map 集合),分頁
注:
? ?queryWrapper 表示實(shí)體對象封裝操作類(可以為 null)
? ?page 表示分頁查詢條件
1
2
3
2、Service 接口方法(CRUD)
使用 代碼生成器 生成的 service 接口中,其繼承了 IService 接口。IService 內(nèi)部進(jìn)一步封裝了 BaseMapper 接口的方法(當(dāng)然也提供了更詳細(xì)的方法)。使用時,可以通過 生成的 mapper 類進(jìn)行 CRUD 操作,也可以通過 生成的 service 的實(shí)現(xiàn)類進(jìn)行 CRUD 操作。(當(dāng)然,自定義代碼執(zhí)行也可以)
此處簡單介紹一下 IService 中封裝的常用方法:
添加數(shù)據(jù):
方法介紹default boolean save(T entity);// 調(diào)用 BaseMapper 的 insert 方法,用于添加一條數(shù)據(jù)。boolean saveBatch(Collection entityList, int batchSize);// 批量插入數(shù)據(jù)
注:
? ?entityList 表示實(shí)體對象集合
? ?batchSize 表示一次批量插入的數(shù)據(jù)量,默認(rèn)為 1000
1
2
3
添加或修改數(shù)據(jù):
方法介紹boolean saveOrUpdate(T entity);// id 若存在,則修改, id 不存在則新增數(shù)據(jù)default boolean saveOrUpdate(T entity, Wrapper updateWrapper);// 先根據(jù)條件嘗試更新,然后再執(zhí)行 saveOrUpdate 操作boolean saveOrUpdateBatch(Collection entityList, int batchSize);// 批量插入并修改數(shù)據(jù)
刪除數(shù)據(jù):
方法介紹default boolean removeById(Serializable id);// 調(diào)用 BaseMapper 的 deleteById 方法,根據(jù) id 刪除數(shù)據(jù)。default boolean removeByMap(Map<String, Object> columnMap);// 調(diào)用 BaseMapper 的 deleteByMap 方法,根據(jù) map 定義字段的條件刪除default boolean remove(Wrapper queryWrapper);// 調(diào)用 BaseMapper 的 delete 方法,根據(jù)實(shí)體類定義的 條件刪除對象。default boolean removeByIds(Collection<? extends Serializable> idList);// 用 BaseMapper 的 deleteBatchIds 方法, 進(jìn)行批量刪除。
修改數(shù)據(jù):
方法介紹default boolean updateById(T entity);// 調(diào)用 BaseMapper 的 updateById 方法,根據(jù) ID 選擇修改。default boolean update(T entity, Wrapper updateWrapper);// 調(diào)用 BaseMapper 的 update 方法,根據(jù) updateWrapper 條件修改實(shí)體對象。boolean updateBatchById(Collection entityList, int batchSize);// 批量更新數(shù)據(jù)
查找數(shù)據(jù):
方法介紹default T getById(Serializable id);// 調(diào)用 BaseMapper 的 selectById 方法,根據(jù) 主鍵 ID 返回數(shù)據(jù)。default List listByIds(Collection<? extends Serializable> idList);// 調(diào)用 BaseMapper 的 selectBatchIds 方法,批量查詢數(shù)據(jù)。default List listByMap(Map<String, Object> columnMap);// 調(diào)用 BaseMapper 的 selectByMap 方法,根據(jù)表字段條件查詢default T getOne(Wrapper queryWrapper);// 返回一條記錄(實(shí)體類保存)。Map<String, Object> getMap(Wrapper queryWrapper);// 返回一條記錄(map 保存)。default int count(Wrapper queryWrapper);// 根據(jù)條件返回 記錄數(shù)。default List list();// 返回所有數(shù)據(jù)。default List list(Wrapper queryWrapper);// 調(diào)用 BaseMapper 的 selectList 方法,查詢所有記錄(返回 entity 集合)。default List<Map<String, Object>> listMaps(Wrapper queryWrapper);// 調(diào)用 BaseMapper 的 selectMaps 方法,查詢所有記錄(返回 map 集合)。default List listObjs();// 返回全部記錄,但只返回第一個字段的值。default <E extends IPage> E page(E page, Wrapper queryWrapper);// 調(diào)用 BaseMapper 的 selectPage 方法,分頁查詢default <E extends IPage<Map<String, Object>>> E pageMaps(E page, Wrapper queryWrapper);// 調(diào)用 BaseMapper 的 selectMapsPage 方法,分頁查詢
注:
? ?get 用于返回一條記錄。
? ?list 用于返回多條記錄。
? ?count 用于返回記錄總數(shù)。
? ?page 用于分頁查詢。
1
2
3
4
5
鏈?zhǔn)秸{(diào)用:
方法介紹default QueryChainWrapper query();// 普通鏈?zhǔn)讲樵僤efault LambdaQueryChainWrapper lambdaQuery();// 支持 Lambda 表達(dá)式的修改default UpdateChainWrapper update();// 普通鏈?zhǔn)叫薷膁efault LambdaUpdateChainWrapper lambdaUpdate();// 支持 Lambda 表達(dá)式的修改
注:
? ?query 表示查詢
? ?update 表示修改
? ?Lambda 表示內(nèi)部支持 Lambda 寫法。
形如:
? ?query().eq("column", value).one();
? ?lambdaQuery().eq(Entity::getId, value).list();
? ?update().eq("column", value).remove();
? ?lambdaUpdate().eq(Entity::getId, value).update(entity);
1
2
3
4
5
6
7
8
9