本文是通過慕課網(wǎng)相關(guān)課程學(xué)習(xí)MyBatisPlus整理的筆記。
MyBatisPlus入門 : - ) 老師講的挺好的,還不會MyBatisPlus的小伙伴門可以聽一下。
MyBatisPlus官網(wǎng)
MyBatisPlus源碼地址
MyBatisPlus架構(gòu)圖(盜用官網(wǎng)的锹引,侵,刪唆香。)
SpringBoot第一個簡單應(yīng)用
- 數(shù)據(jù)庫建表
#創(chuàng)建用戶表
CREATE TABLE user (
id BIGINT(20) PRIMARY KEY NOT NULL COMMENT '主鍵',
name VARCHAR(30) DEFAULT NULL COMMENT '姓名',
age INT(11) DEFAULT NULL COMMENT '年齡',
email VARCHAR(50) DEFAULT NULL COMMENT '郵箱',
manager_id BIGINT(20) DEFAULT NULL COMMENT '直屬上級id',
create_time DATETIME DEFAULT NULL COMMENT '創(chuàng)建時間',
CONSTRAINT manager_fk FOREIGN KEY (manager_id)
REFERENCES user (id)
) ENGINE=INNODB CHARSET=UTF8;
#初始化數(shù)據(jù):
INSERT INTO user (id, name, age, email, manager_id
, create_time)
VALUES (1087982257332887553, '大boss', 40, 'boss@baomidou.com', NULL
, '2019-01-11 14:20:20'),
(1088248166370832385, '王天風(fēng)', 25, 'wtf@baomidou.com', 1087982257332887553
, '2019-02-05 11:12:22'),
(1088250446457389058, '李藝偉', 28, 'lyw@baomidou.com', 1088248166370832385
, '2019-02-14 08:31:16'),
(1094590409767661570, '張雨琪', 31, 'zjq@baomidou.com', 1088248166370832385
, '2019-01-14 09:15:15'),
(1094592041087729666, '劉紅雨', 32, 'lhm@baomidou.com', 1088248166370832385
, '2019-01-14 09:48:16');
- 依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.2</version>
</dependency>
- springboot配置文件
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/test?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
logging:
level:
root: warn
org.ywb.demo.dao: trace
pattern:
console: '%p%m%n'
-
創(chuàng)建相關(guān)包嫌变,如圖:
image.png - 在pojo包中新建和數(shù)據(jù)庫user表映射的類
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
private String managerId;
private LocalDateTime createTime;
}
- 在dao包中創(chuàng)建mapper接口,并集成mybatisPlus的BaseMapper
public interface UserMapper extends BaseMapper<User> {
}
- 在springboot啟動類添加
@MapperScan
掃描dao層接口
@MapperScan("org.ywb.demo.dao")
@SpringBootApplication
public class MybatisPlusDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusDemoApplication.class, args);
}
}
8.編寫測試類
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisPlusDemoApplicationTests {
@Resource
private UserMapper userMapper;
@Test
public void select(){
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
運(yùn)行結(jié)果:
常用注解
MyBatisPlus提供了一些注解供我們在實體類和表信息出現(xiàn)不對應(yīng)的時候使用袋马。通過使用注解完成邏輯上匹配初澎。
注解名稱 | 說明 |
---|---|
@TableName |
實體類的類名和數(shù)據(jù)庫表名不一致 |
@TableId |
實體類的主鍵名稱和表中主鍵名稱不一致 |
@TableField |
實體類中的成員名稱和表中字段名稱不一致 |
@Data
@TableName("t_user")
public class User {
@TableId("user_id")
private Long id;
@TableField("real_name")
private String name;
private Integer age;
private String email;
private Long managerId;
private LocalDateTime createTime;
}
排除實體類中非表字段
- 使用
transient
關(guān)鍵字修飾非表字段,但是被transient
修飾后虑凛,無法進(jìn)行序列化碑宴。 - 使用
static
關(guān)鍵字,因為我們使用的是lombok框架生成的get/set方法桑谍,所以對于靜態(tài)變量延柠,我們需要手動生成get/set方法。 - 使用
@TableField(exist = false)
注解
CURD
BaseMapper中封裝了很多關(guān)于增刪該查的方法锣披,后期自動生成贞间,我們直接調(diào)用接口中的相關(guān)方法即可完成相應(yīng)的操作。
BaseMapper
部分代碼
public interface BaseMapper<T> extends Mapper<T> {
int insert(T entity);
int deleteById(Serializable id);
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
int updateById(@Param(Constants.ENTITY) T entity);
...
}
插入一條記錄測試:
@Test
public void insert(){
User user = new User();
user.setAge(31);
user.setManagerId(1088250446457389058L);
user.setCreateTime(LocalDateTime.now());
int insert = userMapper.insert(user);
System.out.println("影像記錄數(shù):"+insert);
}
條件構(gòu)造器查詢
除了BaseMapper
中提供簡單的增刪改查方法之外雹仿,還提供了很多關(guān)于區(qū)間查詢增热,多表連接查詢,分組等等查詢功能胧辽,實現(xiàn)的類圖如下所示:
通過觀察類圖可知峻仇,我們需要這些功能時,只需要創(chuàng)建
QueryWrapper
對象即可邑商。
- 模糊查詢
/**
* 查詢名字中包含'雨'并且年齡小于40
* where name like '%雨%' and age < 40
*/
@Test
public void selectByWrapper(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name","雨").lt("age",40);
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
- 嵌套查詢
/**
* 創(chuàng)建日期為2019年2月14日并且直屬上級姓名為王姓
* date_format(create_time,'%Y-%m-%d') and manager_id in (select id from user where name like '王%')
*/
@Test
public void selectByWrapper2(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.apply("date_format(create_time,'%Y-%m-%d')={0}","2019-02-14")
.inSql("manager_id","select id from user where name like '王%'");
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
注意
上面的日期查詢使用的是占位符的形式進(jìn)行查詢摄咆,目的就是為了防止SQL注入的風(fēng)險。
apply方法的源碼
/**
* 拼接 sql
* <p>!! 會有 sql 注入風(fēng)險 !!</p>
* <p>例1: apply("id = 1")</p>
* <p>例2: apply("date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")</p>
* <p>例3: apply("date_format(dateColumn,'%Y-%m-%d') = {0}", LocalDate.now())</p>
*
* @param condition 執(zhí)行條件
* @return children
*/
Children apply(boolean condition, String applySql, Object... value);
SQL 注入的例子:
queryWrapper.apply("date_format(create_time,'%Y-%m-%d')=2019-02-14 or true=true") .inSql("manager_id","select id from user where name like '王%'");
sql注入例子
- and & or
/**
* 名字為王姓人断,(年齡小于40或者郵箱不為空)
*/
@Test
public void selectByWrapper3(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.likeRight("name","王").and(wq-> wq.lt("age",40).or().isNotNull("email"));
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
- between & and
/**
* 名字為王姓吭从,(年齡小于40,并且年齡大于20恶迈,并且郵箱不為空)
*/
@Test
public void selectWrapper4(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.likeRight("name", "王").and(wq -> wq.between("age", 20, 40).and(wqq -> wqq.isNotNull("email")));
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
- nested
/**
* (年齡小于40或者郵箱不為空)并且名字為王姓
* (age<40 or email is not null)and name like '王%'
*/
@Test
public void selectWrapper5(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.nested(wq->wq.lt("age",40).or().isNotNull("email")).likeRight("name","王");
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
- in
/**
* 年齡為30,31,35,34的員工
*/
@Test
public void selectWrapper6(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.in("age", Arrays.asList(30,31,34,35));
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
- last 有SQL注入的風(fēng)險I稹!!
/**
* 無視優(yōu)化規(guī)則直接拼接到 sql 的最后(有sql注入的風(fēng)險,請謹(jǐn)慎使用)
* <p>例: last("limit 1")</p>
* <p>注意只能調(diào)用一次,多次調(diào)用以最后一次為準(zhǔn)</p>
*
* @param condition 執(zhí)行條件
* @param lastSql sql語句
* @return children
*/
Children last(boolean condition, String lastSql);
/**
* 只返回滿足條件的一條語句即可
* limit 1
*/
@Test
public void selectWrapper7(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.in("age", Arrays.asList(30,31,34,35)).last("limit 1");
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
- 查詢指定部分列
/**
* 查找為王姓的員工的姓名和年齡
*/
@Test
public void selectWrapper8(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("name","age").likeRight("name","王");
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
- 使用過濾器查詢指定列
/**
* 查詢所有員工信息除了創(chuàng)建時間和員工ID列
*/
@Test
public void selectWrapper9(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select(User.class,info->!info.getColumn().equals("create_time")
&&!info.getColumn().equals("manager_id"));
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
condition 的作用
在我們調(diào)用的查詢語句中鸭廷,通過查看源碼(這里以apply
方法為例)可以看出枣抱,每個查詢方法的第一個參數(shù)都是boolean類型的參數(shù)熔吗,重載方法中默認(rèn)給我們傳入的都是true辆床。
default Children apply(String applySql, Object... value) {
return apply(true, applySql, value);
}
Children apply(boolean condition, String applySql, Object... value);
這個condition的作用是為true時,執(zhí)行其中的SQL條件桅狠,為false時讼载,忽略設(shè)置的SQL條件。
實體作為條件構(gòu)造方法的參數(shù)
在web開發(fā)中中跌,controller層常常會傳遞給我們一個用戶的對象咨堤,比如通過用戶姓名和用戶年齡查詢用戶列表。
我們可以將傳遞過來的對象直接以構(gòu)造參數(shù)的形式傳遞給QueryWrapper
漩符,MyBatisPlus會自動根據(jù)實體對象中的屬性自動構(gòu)建相應(yīng)查詢的SQL語句一喘。
@Test
public void selectWrapper10(){
User user = new User();
user.setName("劉紅雨");
user.setAge(32);
QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
如果想通過對象中某些屬性進(jìn)行模糊查詢,我們可以在跟數(shù)據(jù)庫表對應(yīng)的實體類中相應(yīng)的屬性標(biāo)注注解即可嗜暴。
比如我們想通過姓名進(jìn)行模糊查詢用戶列表凸克。
@TableField(condition = SqlCondition.LIKE)
private String name;
@Test
public void selectWrapper10(){
User user = new User();
user.setName("紅");
user.setAge(32);
QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
Lambda條件構(gòu)造器
MybatisPlus提供了4種方式創(chuàng)建lambda條件構(gòu)造器,前三種分別是這樣的
LambdaQueryWrapper<User> lambdaQueryWrapper = new QueryWrapper<User>().lambda();
LambdaQueryWrapper<User> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
LambdaQueryWrapper<User> lambdaQueryWrapper2 = Wrappers.lambdaQuery();
- 查詢名字中包含‘雨’并且年齡小于40的員工信息
@Test
public void lambdaSelect(){
LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.lambdaQuery();
lambdaQueryWrapper.like(User::getName,"雨").lt(User::getAge,40);
List<User> userList = userMapper.selectList(lambdaQueryWrapper);
userList.forEach(System.out::println);
}
QueryWrapper類已經(jīng)提供了很強(qiáng)大的功能闷沥,而lambda條件構(gòu)造器做的和QueryWrapper的事也是相同的為什么要冗余的存在lambda條件構(gòu)造器呢萎战?
QueryWrapper是通過自己寫表中相應(yīng)的屬性進(jìn)行構(gòu)造where條件的,容易發(fā)生拼寫錯誤舆逃,在編譯時不會報錯蚂维,只有運(yùn)行時才會報錯,而lambda條件構(gòu)造器是通過調(diào)用實體類中的方法路狮,如果方法名稱寫錯虫啥,直接進(jìn)行報錯,所以lambda的糾錯功能比QueryWrapper要提前很多奄妨。
舉個例子:
查找姓名中包含“雨”字的員工信息涂籽。
使用QueryWrapperqueryWrapper.like("name","雨");
使用lambda
lambdaQueryWrapper.like(User::getName,"雨");
如果在拼寫name的時候不小心,寫成了naem,程序并不會報錯展蒂,但是如果把方法名寫成了getNaem程序立即報錯又活。
第四種lambda構(gòu)造器
細(xì)心的人都會發(fā)現(xiàn)無論是之前的lambda構(gòu)造器還是queryWrapper,每次編寫完條件構(gòu)造語句后都要將對象傳遞給mapper 的selectList方法锰悼,比較麻煩柳骄,MyBatisPlus提供了第四種函數(shù)式編程方式,不用每次都傳箕般。
- 查詢名字中包含“雨”字的耐薯,并且年齡大于20的員工信息
@Test
public void lambdaSelect(){
List<User> userList = new LambdaQueryChainWrapper<>(userMapper).like(User::getName, "雨").ge(User::getAge, 20).list();
userList.forEach(System.out::println);
}
自定義SQL
-
在resources資源文件夾下新建mapper文件夾,并將mapper文件夾的路徑配置到配置文件中
image.png
mybatis-plus:
mapper-locations: mapper/*.xml
- 在mapper 文件夾中新建UserMapper.xml。
- 像mybatis那樣在UseMapper接口中寫接口曲初,在UserMapper接口中寫SQL即可体谒。
UserMapper
public interface UserMapper extends BaseMapper<User> {
/**
* 查詢所有用戶信息
* @return list
*/
List<User> selectAll();
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.ywb.demo.dao.UserMapper">
<select id="selectAll" resultType="org.ywb.demo.pojo.User">
select * from user
</select>
</mapper>
分頁查詢
MyBatis分頁提供的是邏輯分頁,每次將所有數(shù)據(jù)查詢出來臼婆,存儲到內(nèi)存中抒痒,然后根據(jù)頁容量,逐頁返回颁褂。如果表很大故响,無疑是一種災(zāi)難!
MyBatisPlus物理分頁插件
- 新建config類颁独,在config類中創(chuàng)建
PaginationInterceptor
對象
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
- 測試:查詢年齡大于20 的用戶信息彩届,并以每頁容量為兩條分頁的形式返回。
@Test
public void selectPage(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.ge("age",20);
//設(shè)置當(dāng)前頁和頁容量
Page<User> page = new Page<>(1, 2);
IPage<User> userIPage = userMapper.selectPage(page, queryWrapper);
System.out.println("總頁數(shù):"+userIPage.getPages());
System.out.println("總記錄數(shù):"+userIPage.getTotal());
userIPage.getRecords().forEach(System.out::println);
}
- 測試:不查詢總記錄數(shù)誓酒,分頁查詢
IPage類的構(gòu)造參數(shù)提供了參數(shù)的重載,第三個參數(shù)為false時樟蠕,不會查詢總記錄數(shù)。
public Page(long current, long size, boolean isSearchCount) {
this(current, size, 0, isSearchCount);
}
~~·
## 更新
1. 通過userMapper提供的方法更新用戶信息
~~~java
@Test
public void updateTest1(){
User user = new User();
user.setId(1088250446457389058L);
user.setEmail("update@email");
int rows = userMapper.updateById(user);
System.out.println(rows);
}
- 使用UpdateWrapper更新數(shù)據(jù)(相當(dāng)于使用聯(lián)合主鍵)
@Test
public void updateTest2(){
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("name","李藝偉").eq("age",26);
User user = new User();
user.setEmail("update2@email");
int rows = userMapper.update(user, updateWrapper);
System.out.println(rows);
}
- 當(dāng)我們更新少量用戶信息的時候靠柑,可以不用創(chuàng)建對象寨辩,直接通過調(diào)用set方法更新屬性即可。
@Test
public void updateTest3(){
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("name","李藝偉").eq("age",26).set("email","update3@email.com");
userMapper.update(null,updateWrapper);
}
- 使用lambda更新數(shù)據(jù)
@Test
public void updateByLambda(){
LambdaUpdateWrapper<User> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
lambdaUpdateWrapper.eq(User::getName,"李藝偉").eq(User::getAge,26).set(User::getAge,27);
userMapper.update(null,lambdaUpdateWrapper);
}
刪除
刪除方式和update極其類似病往。
AR模式(Active Record)
直接通過實體類完成對數(shù)據(jù)的增刪改查捣染。
- 實體類繼承Model類
@Data
@EqualsAndHashCode(callSuper = false)
public class User extends Model<User> {
private Long id;
@TableField(condition = SqlCondition.LIKE)
private String name;
private Integer age;
private String email;
private Long managerId;
private LocalDateTime createTime;
}
Model類中封裝了很多增刪改查方法,不用使用UserMapper即可完成對數(shù)據(jù)的增刪改查停巷。
- 查詢所有用戶信息
@Test
public void test(){
User user = new User();
user.selectAll().forEach(System.out::println);
}
主鍵策略
MyBatisPlus的主鍵策略封裝在IdType
枚舉類中耍攘。
@Getter
public enum IdType {
/**
* 數(shù)據(jù)庫ID自增
*/
AUTO(0),
/**
* 該類型為未設(shè)置主鍵類型(將跟隨全局)
*/
NONE(1),
/**
* 用戶輸入ID
* <p>該類型可以通過自己注冊自動填充插件進(jìn)行填充</p>
*/
INPUT(2),
/* 以下3種類型、只有當(dāng)插入對象ID 為空畔勤,才自動填充蕾各。 */
/**
* 全局唯一ID (idWorker)
*/
ID_WORKER(3),
/**
* 全局唯一ID (UUID)
*/
UUID(4),
/**
* 字符串全局唯一ID (idWorker 的字符串表示)
*/
ID_WORKER_STR(5);
private final int key;
IdType(int key) {
this.key = key;
}
}
在實體類中對應(yīng)數(shù)據(jù)庫中的主鍵id屬性上標(biāo)注注解TableId(type='xxx')
即可完成主鍵配置。
@TableId(type = IdType.AUTO)
private Long id;
這種配置方式的主鍵策略只能在該表中生效庆揪,但是其他表還需要進(jìn)行配置式曲,為了避免冗余,麻煩缸榛,MybatisPlus提供了全局配置吝羞,在配置文件中配置主鍵策略即可實現(xiàn)。
mybatis-plus:
mapper-locations: mapper/*.xml
global-config:
db-config:
id-type: auto
如果全局策略和局部策略全都設(shè)置内颗,局部策略優(yōu)先钧排。
基本配置
mybatis-plus:
mapper-locations: mapper/*.xml
global-config:
db-config:
# 主鍵策略
id-type: auto
# 表名前綴
table-prefix: t
# 表名是否使用下劃線間隔,默認(rèn):是
table-underline: true
# 添加mybatis配置文件路徑
config-location: mybatis-config.xml
# 配置實體類包地址
type-aliases-package: org.ywb.demo.pojo
# 駝峰轉(zhuǎn)下劃線
configuration:
map-underscore-to-camel-case: true
- 附錄
- mybatisPlus進(jìn)階功能請戳 MyBatisPlus學(xué)習(xí)整理(二)
- 源碼地址:https://github.com/xiao-ren-wu/notebook/tree/master/mybatis-plus-demo