Mybatis-Plus学习笔记

1.快速入门

  • 数据库创建
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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)
);

DELETE FROM user;

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');
  • 新建springboot项目
  • 配置文件
1
2
3
4
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
  • mapper接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.codelorin.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.codelorin.pojo.User;
import org.springframework.stereotype.Repository;

/**
* @description: 只需要继承BaseMapper,泛型填写实体类,所有的CURD操作就已经完成了
* @author: CodeLorin
* @date: 2021/10/8 23:10
*/
@Repository
public interface UserMapper extends BaseMapper<User> {

}

  • 扫描mapper文件夹
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.codelorin;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.codelorin.mapper")
@SpringBootApplication
public class MybatisPlusStudyApplication {

public static void main(String[] args) {
SpringApplication.run(MybatisPlusStudyApplication.class, args);
}

}

  • test
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.codelorin;

import com.codelorin.mapper.UserMapper;
import com.codelorin.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class MybatisPlusStudyApplicationTests {
@Autowired
private UserMapper userMapper;

@Test
void contextLoads() {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);

}

}

2.配置日志

1
2
# 配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

3.CURD

1.插入

1
2
3
4
5
6
7
@TableId(type = IdType.AUTO)   
AUTO(0), //数据库自增
NONE(1), //没有
INPUT(2), //手动输入
ID_WORKER(3),//雪花
UUID(4), //uuid
ID_WORKER_STR(5);//截取字符串

主键生成策略

雪花算法

Twitter开源的分布式id生成算法

数据库主键自增

1
2
3
4
5
6
User user = new User();
user.setAge(18);
user.setEmail("codelorin@163.com");
user.setName("codelorin");

int result = userMapper.insert(user);

2.更新

1
2
3
4
5
User user = new User();
user.setId(6L);
user.setEmail("bylorin@163.com");
user.setName("codelorin");
userMapper.updateById(user);

3.自动填充时间

1.新增字段 create_time update_time

1
2
3
4
5
6
7
8
9
10
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '姓名',
`age` int(11) NULL DEFAULT NULL COMMENT '年龄',
`email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '邮箱',
`create_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
`update_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0),
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1446495940495015940 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

3.1.数据库实现

4.乐观锁

十分乐观,总是认为不会出现问题,无论都不加锁,如果出现了问题,再次更新测试

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败

5.悲观锁

十分悲观,总是认为会出现问题,无论干什么都会上锁,再去操作

6.查询操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
public void testSelect() {
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);
}

@Test
public void testSelectByMap() {
HashMap<String, Object> map = new HashMap<>();
map.put("name", "10ng123");
userMapper.selectByMap(map);
}

7.分页实现

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
package com.codelorin.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;


import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* @ClassName MybatisPlusConfig
* @Description TODO
* @Author CodeLorin
* @Date 2021/11/18 19:49
* @Version 1.0
*/

@Configuration
@MapperScan("com.codelorin.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}


}

使用

1
2
3
4
5
6
7
public void testPage() {
Page<User> page = new Page<>(2, 5);
userMapper.selectPage(page, null);
List<User> records = page.getRecords();
records.forEach(System.out::println);
System.out.println(page.getTotal());
}

8.删除

1
2
3
4
public void delete() {
int i = userMapper.deleteById(2L);
System.out.println(i);
}

9.逻辑删除

1
2
3
mybatis-plus.global-config.db-config.logic-delete-field=deleted
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
1
2
@TableLogic
private Integer deleted;

4.性能分析插件

见官网

5.条件构造器

1
2
3
4
5
6
7
8
//模糊查询
@Test
void test4() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.notLike("name", "lorin").likeRight("email", "t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}