测试环境在上一篇MyBatis-Plus概述中搭建完成!

Mapper CRUD 接口

image-20200421175852672

Insert

image-20200421175907600

Delete

image-20200421175935055

Update

image-20200421180002971

Select

image-20200421180032760

image-20200421180052314

配置日志

我们现在所有的sql现在是不可见的,我们希望知道它是怎么执行的,所以我们必须要看日志。配置配置文件开启日志输出。

image-20200418101944653

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

查看测试查询全部效果

image-20200418102631130

插入操作

userMapper.insert();参数是实体类对象

image-20200418103341789

1
2
3
4
5
6
7
8
9
10
// 测试插入
@Test
void testInsert() {
User user = new User();
user.setName("kylin");
user.setAge(3);
user.setEmail("zhang171346168@qq.com");
int result = userMapper.insert(user);//id会自动生成全局唯一id
System.out.println(result);
}

运行测试

image-20200418103658984

发现自动帮我们生成一个全局唯一主键ID值!

image-20200418103753187

主键生成策略

由上可知,当我们不配主键ID时,MyBatisPlus会帮我们自动生成一个全局唯一的主键值。哪它是按什么思路生成的呢?我们能配置主键生成策略吗?答案是可以的。

我们可以通过在实体类上的@TableId进行配置生成策略

描述
AUTO 数据库ID自增
NONE 无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
INPUT insert前自行set主键值
ASSIGN_ID 分配ID(主键类型为Number(Long和Integer)或String)(since 3.3.0),使用接口IdentifierGenerator的方法nextId(默认实现类为DefaultIdentifierGenerator雪花算法)
ASSIGN_UUID 分配UUID,主键类型为String(since 3.3.0),使用接口IdentifierGenerator的方法nextUUID(默认default方法)
ID_WORKER 分布式全局唯一ID 长整型类型(please use ASSIGN_ID)
UUID 32位UUID字符串(please use ASSIGN_UUID)
ID_WORKER_STR 分布式全局唯一ID 字符串类型(please use ASSIGN_ID)

默认值为ID_WORKER 全局唯一id。也就是上文生成的。(MyBatisPlus新版发生改变例如3.3.1)

image-20200418104654596

其采用的算法是雪花算法

snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为 毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味 着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。可以保证几乎全球唯 一!

主键自增

以配置主键自增为例。

1.首先我们要在实体类主键字段上加上@TableId(type = IdType.AUTO)

image-20200418105341893

2.主键自增需要修改数据库字段为自增

image-20200418105504561

3.再次测试插入

image-20200418105649526

image-20200418105734317

此时的ID值则在原来去基础上自增1.其他主键策略修改type值就可以了。

更新操作

userMapper.updateById();注意参数是实体类对象,通过id作为条件进行更新

测试之前将主键生成策略改为input手动输入

image-20200418110347577

编写测试

image-20200418113014530

1
2
3
4
5
6
7
8
9
10
@Test
void testUpdate() {
User user = new User();
user.setId(5L);
user.setName("kylin");
user.setAge(12);
user.setEmail("zhang171346168@qq.com");
int i = userMapper.updateById(user);
System.out.println(i);
}

image-20200418113136712

image-20200418113226874

自动填充

创建时间、修改时间!这些个操作一遍都是自动化完成的,我们不希望手动更新!

阿里巴巴开发手册:所有的数据库表:gmt_create、gmt_modified几乎所有的表都要配置上!而且需 要自动化!

方式一:数据库级别(工作中不允许你修改数据库)

1、在表中新增字段 create_time, update_time

image-20200418173228151

image-20200418173244776

2.再次测试插入方法前,我们需要先把实体类的属性与字段同步!

image-20200418173359316

image-20200418174125747

MyBatisPlus是默认开启驼峰命名的。也就是实体类中属性createTime对应字段create_time。如果数据库中为create_time为createTime则会出现映射错误。

如果出现上面这种情况则需要配置MyBatisPlus的配置文件。关闭驼峰命名

1
mybatis-plus.configuration.map-underscore-to-camel-case=false

测试插入方法

image-20200418180244122

image-20200418180454812

3.插入成功后查看数据库

image-20200418180537185

发现数据库中已经更新了创建时间和更新时间。

注意:SpringBoot配置数据库时时区为UTC会造成写入数据库时与中国北京时间相差8小时。这时候我们就要修改时区为serverTimezone=GMT%2B8

image-20200418181209383

方式二:代码级别

1.删除数据库的默认值、更新操作!(navicat中把这两栏删掉,再重新创建)

image-20200418190111259

2.实体类字段属性上需要增加注解@TableField根据实际情况。updateTime应在对其进行任何操作时都要更新时间。所以要在插入和更新时都更新改字段。

image-20200418190225416

image-20200418190342657

3.编写处理器来处理这个注解,在handle包下创建一个MyMetaObjectHandler 类实现 MetaObjectHandler接口,重写方法。

image-20200418190818980

4、测试插入

image-20200418190905317

image-20200418190942183

image-20200418191006846

5.测试更新

image-20200418191027550

image-20200418191103111

查看数据库发现改用户的更新时间发生改变。成功!

image-20200418191218433

乐观锁

乐观锁 : 故名思意十分乐观,它总是认为不会出现问题,无论干什么不去上锁!如果出现了问题, 再次更新值测试。

悲观锁:故名思意十分悲观,它总是认为总是出现问题,无论干什么都会上锁!再去操作!

乐观锁实现方式

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

image-20200421134936267

乐观锁插件测试

1.给数据库中增加version字段!

image-20200421135526025

image-20200421135556152

2.我们实体类加对应的字段。使用@Version注解

image-20200421135724020

image-20200421135906374

3.编写MybatisPlus配置类,注册组件。

image-20200421142200316

1
2
3
4
5
6
7
8
9
10
11
//@MapperScan("com.kylin.mapper")//扫描mapper文件夹
@EnableTransactionManagement//自动管理事务
@Configuration//配置类
public class MybatisPlusConfig {

//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}

4.测试一下

image-20200421142906267

1
2
3
4
5
6
7
8
9
10
11
12
//测试乐观锁
@Test
void testOptimisticLocker() {
//1.查询用户信息
User user = userMapper.selectById(1L);
//2.修改用户信息
user.setName("kylin");
user.setEmail("zhang171346168@qq.com");
//3.执行更新操作
int i = userMapper.updateById(user);
System.out.println(i);
}

image-20200421143155430

image-20200421143223927

正常更新~

5.模拟另一个线程执行了插队操作测试

image-20200421143411553

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//测试乐观锁失败~多线程下
@Test
void testOptimisticLocker2() {
//线程1
User user = userMapper.selectById(1L);
user.setName("kylin111");
user.setEmail("zhang171346168@qq.com");

//模拟另一个线程执行了插队操作
User user2 = userMapper.selectById(1L);
user2.setName("kylin222");
user2.setEmail("zhang171346168@qq.com");
//执行更新操作
userMapper.updateById(user2);
userMapper.updateById(user);//如果没有乐观锁就会覆盖插队线程的值
}

image-20200421143905436

image-20200421143934868

查询操作

userMapper.selectById()

image-20200421152508678

1
2
3
4
5
@Test
void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}

image-20200421152555715

批量查询userMapper.selectBatchIds()

image-20200421152713919

1
2
3
4
5
6
//测试批量查询
@Test
void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1,2,3));
users.forEach(System.out::println);
}

image-20200421152824818

按条件查询之一 通过mapuserMapper.selectByMap()

image-20200421152919723

1
2
3
4
5
6
7
8
9
10
11
12
//测试条件查询之一 通过map
@Test
void testSelectByBatchIds(){
HashMap<String,Object> map = new HashMap<>();

//自定义查询
map.put("name","kylin");
map.put("age",3);

List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}

image-20200421153041490

分页查询

进行分页查询可以使用原始的limit进行分页,或者使用pageHelper第三方插件。而MaBatisPlus也内置了分页插件。

1.在MybatisPlus的配置类中注册拦截器组件

image-20200421153601541

image-20200421153639174

1
2
3
4
5
//注册分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}

2.测试。直接使用Page对象即可! userMapper.selectPage(page,null);//条件表达式为空

image-20200421153931573

1
2
3
4
5
6
7
8
//测试分页查询
@Test
void testPage(){
//参数一:当前页 参数二:页面大小
Page<User> page = new Page<>(2,5);
userMapper.selectPage(page,null);//条件表达式为空
page.getRecords().forEach(System.out::println);
}

image-20200421154354446

image-20200421154456700

删除操作

image-20200421154841654

根据 id 删除记录userMapper.deleteById()

image-20200421154909813

1
2
3
4
5
//测试删除。根据id删除
@Test
void testDeleteById(){
userMapper.deleteById(1251338727926538241L);
}

image-20200421155035383

image-20200421155058830

通过id批量删除userMapper.deleteBatchIds()

image-20200421155214462

1
2
3
4
5
//通过id批量删除
@Test
void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1251338727926538242L,1251338727926538243L));
}

image-20200421155304272

image-20200421155318666

通过map删除userMapper.deleteByMap()

image-20200421155414068

1
2
3
4
5
6
7
//通过map删除
@Test
void testDeleteMap(){
HashMap<String,Object> map = new HashMap<>();
map.put("name","kylin222");
userMapper.deleteByMap(map);
}

image-20200421155520168

image-20200421155546415

逻辑删除

物理删除 :从数据库中直接移除

逻辑删除 :再数据库中没有被移除,而是通过一个变量来让他失效! deleted = 0 => deleted = 1

应用场景:管理员可以查看被删除的记录!防止数据的丢失,类似于回收站!

1.在数据表中增加一个 deleted 字段

image-20200421160110851

image-20200421160120833

2.实体类中增加属性。通过@TableLogic

image-20200421160252157

3.在MybatisPlus配置类中注册逻辑删除。3.1.1不用注册Bean

image-20200421160702126

image-20200421160451303

1
2
3
4
5
//逻辑删除组件
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}

4.在SpringBoot配置文件中配置逻辑删除的默认值

image-20200421160804499

image-20200421160843110

1
2
3
#配置逻辑删除 默认为0 逻辑删除后为1
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

5.通过删除操作进行测试

image-20200421161108001

image-20200421161230236

image-20200421161312197

在使用查询全部操作,看看是否能查询到此条记录。

image-20200421161436458

image-20200421161602287

性能分析插件

我们在平时的开发中,会遇到一些慢sql。druid数据源也是有性能分析的。

作用:性能分析拦截器,用于输出每条 SQL 语句及其执行时间 MP也提供性能分析插件,如果超过这个时间就停止运行!

性能分析是需要消耗系统性能的,所以设置当处于开发环境dev,和测试环境test中开启。

1.配置MyBatis配置类注册插件

image-20200421164921642

2.测试。为了展示效果设置了sql语句运行超过1毫米就不执行。随便点击一个测试

image-20200421165203781

image-20200421165440586

使用性能分析插件能帮我们直观的展示Sql语句运行的效率~