MyBatisPlus笔记01 CRUD

https://www.bilibili.com/video/BV1rE41197jR
p1~25
数据库准备
1 | -- 创建测试表 |
创建工程
导入依赖
1 | <dependencies> |
配置文件
log4j.properties
1 | DEBUG,A1 = |
application.properties
1 | itcast-mp-springboot = |
实体类
使用lombok注解生成get、set方法
使用MybatisPlus注解指定表名
1 | package com.coconutnut.demo.pojo; |
用@TableId指定id的增长策略
@TableField
可解决的问题:
对象中的属性名和字段名不一致的问题(非驼峰)
1
2
private String mail;对象中的属性字段在表中不存在的问题
1
2
private String address;查询时不返回该字段的值
1
2
private String password;
Mapper接口
1 | package com.coconutnut.demo.mapper; |
SpringBoot启动类
使用@MapperScan设置mapper接口的扫描包
1 | package com.coconutnut.demo; |
项目结构

测试
1 | package com.coconutnut.demo; |
输出

DEBUG 依赖重复
1 | SLF4J: Class path contains multiple SLF4J bindings. |
删除依赖中的
1 | <dependency> |
CRUD
查看UserMapper继承的BaseMapper源码

CRUD方法都有了
官网文档
https://mybatis.plus/guide/crud-interface.html#mapper-crud-%E6%8E%A5%E5%8F%A3
直接测试
插入
1 | // 插入一条记录 |
1 | package com.coconutnut.demo; |
运行后,数据库变化

输出

更新
1 | // 根据 whereEntity 条件,更新记录 |
根据id更新
1 |
|
执行后

根据条件更新
QueryWrapper
1 |
|
wrapper中设置属性用的是mysql表中的名称
执行后

UpdateWrapper
1 |
|
执行后

删除
1 | // 根据 entity 条件,删除记录 |
deleteById
1 |
|
执行后

deleteByMap
1 |
|
执行后

没有符合条件的
delete
1 |
|
推荐使用用法2
deleteByIds
1 |
|
查询
1 | // 根据 ID 查询 |
selectById
1 |
|
执行后

没查到为null
selectOne
不存在返回null
查到多条报错
1 |
|
输出
1 | User(id=2, userName=lisi, password=123456, name=李四, age=20, email=test2@itcast.cn) |
selectBatchIds
1 |
|
执行后

selectCount
1 |
|
输出
1 | count = 2 |
selectList
1 |
|
执行后

selectPage
配置分页插件
1 | import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; |
有了这个配置类之后,DemoApplication中的@MapperScan可以去掉
1 |
|
执行后
