目录
一、MyBatis-Plus简介
1、简介
2、特性
1、依赖少:仅仅依赖 Mybatis 以及 Mybatis-Spring 。
2、损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作 。
3、预防Sql注入:内置 Sql 注入剥离器,有效预防Sql注入攻击 。
4、通用CRUD操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求 。
5、多种主键策略:支持多达4种主键策略(内含分布式唯一ID生成器),可自由配置,完美解决主键问题 。
6、支持热加载:Mapper 对应的 XML 支持热加载,对于简单的 CRUD 操作,甚至可以无 XML 启动
7、支持ActiveRecord:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可实现基本 CRUD 操作
8、支持代码生成:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码(生成自定义文件,避免开发重复代码),支持模板引擎、有超多自定义配置等。
9、支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )。
10、支持关键词自动转义:支持数据库关键词(order、key…)自动转义,还可自定义关键词 。
11、内置分页插件:基于 Mybatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通List查询。
12、内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能有效解决慢查询 。
13、内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,预防误操作。
14、默认将实体类的类名查找数据库中的表,使用@TableName(value="table1")注解指定表名,@TableId指定表主键,若字段与表中字段名保持一致可不加注解。
3、支持数据库
4、框架结构
二、环境搭建
1、创建表
CREATE DATABASE `mybatisplus`;
use `mybatisplus`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2、添加数据
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');
3、搭建开发环境
使用 Spring Initializr 快速初始化一个 Spring Boot 工程
4、引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
5、idea中安装lombok插件
6、配置application.yml
spring: # 配置数据源信息
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatisplus?characterEncoding=utf-8&serverTimezone=GMT%2B8&userSSL=false
username: username
password: [assword
7、配置启动类

8、添加实体
/*
* @NoArgsConstructor 是添加一个无参数的构造器
* @AllArgsConstructor在类上使用,这个注解可以生成全参构造函数,且默认不生成无参构造函数。
* @TableName注解主要是实现实体类型和数据库中的表实现映射。
* */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User {
@TableId(value = "uid")
private Long uid;
private String name;
private Integer age;
private String email;
private Integer sex;
}
9、添加mapper
10、测试
@Autowired
private UserMapper userMapper;
@Test
public void testselect(){
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
三、基本CRUD
public interface BaseMapper<T> extends Mapper<T> { /** * 插入一条记录 * * @param entity 实体对象 */ int insert(T entity); /** * 根据 ID 删除 * * @param id 主键ID */ int deleteById(Serializable id); /** * 根据 columnMap 条件,删除记录 * * @param columnMap 表字段 map 对象 */ int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); /** * 根据 entity 条件,删除记录 * * @param wrapper 实体对象封装操作类(可以为 null) */ int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper); /** * 删除(根据ID 批量删除) * * @param idList 主键ID列表(不能为 null 以及 empty) */ int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); /** * 根据 ID 修改 * * @param entity 实体对象 */ int updateById(@Param(Constants.ENTITY) T entity); /** * 根据 whereEntity 条件,更新记录 * * @param entity 实体对象 (set 条件值,可以为 null) * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句) */ int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper); /** * 根据 ID 查询 * * @param id 主键ID */ T selectById(Serializable id); /** * 查询(根据ID 批量查询) * * @param idList 主键ID列表(不能为 null 以及 empty) */ List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); /** * 查询(根据 columnMap 条件) * * @param columnMap 表字段 map 对象 */ List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); /** * 根据 entity 条件,查询一条记录 * * @param queryWrapper 实体对象封装操作类(可以为 null) */ T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 Wrapper 条件,查询总记录数 * * @param queryWrapper 实体对象封装操作类(可以为 null) */ Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 entity 条件,查询全部记录 * * @param queryWrapper 实体对象封装操作类(可以为 null) */ List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 Wrapper 条件,查询全部记录 * * @param queryWrapper 实体对象封装操作类(可以为 null) */ List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 Wrapper 条件,查询全部记录 * <p>注意: 只返回第一个字段的值</p> * * @param queryWrapper 实体对象封装操作类(可以为 null) */ List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 entity 条件,查询全部记录(并翻页) * * @param page 分页查询条件(可以为 RowBounds.DEFAULT) * @param queryWrapper 实体对象封装操作类(可以为 null) */ <E extends IPage<T>> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 Wrapper 条件,查询全部记录(并翻页) * * @param page 分页查询条件 * @param queryWrapper 实体对象封装操作类 */ <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); }
1、插入
@Test
public void s(){
System.out.println(userMapper.insert(new User("小明1", 55, "cds")));
System.out.println(userMapper.insert(new User("小明2", 40, "10")));
System.out.println(userMapper.insert(new User("小明3", 60, "10")));
System.out.println(userMapper.insert(new User("小明4", 80, "cds")));
}
2、删除
a>通过id删除记录
@Test
public void delect(){
System.out.println(userMapper.deleteById(1527478582870392834L));
}
b>通过id批量删除记录
@Test
public void delect(){
List<Long> list= Arrays.asList(2L,3L);
System.out.println(userMapper.deleteBatchIds(list));
}
c>通过map条件删除记录
@Test
public void delect(){
Map<String,Object> map=new HashMap<>();
map.put("email","cds");
System.out.println(userMapper.deleteByMap(map));
}
3、修改
@Test
public void update(){
User user=new User();
user.setId(1L);
user.setName("update");
user.setEmail("1234567890");
System.out.println(userMapper.updateById(user));
}
4、查询
a>根据id查询用户信息
@Test
public void select(){
System.out.println(userMapper.selectById(4L));
}
b>根据多个id查询多个用户信息
@Test
public void select(){
List<Long> list= Arrays.asList(1527488780829806593L,1527488780762697730L,5L);
List<User> list1 = userMapper.selectBatchIds(list);
list1.forEach(System.out::println);
}
c>通过map条件查询用户信息
@Test
public void select(){
Map<String,Object> map=new HashMap<>();
map.put("name","小明3");
map.put("age",20);
System.out.println(userMapper.selectByMap(map));
}
d>查询所有数据
@Test
public void select(){
System.out.println(userMapper.selectList(null));
}
5、通用Service
说明: .
●通用Service CRUD封装IService接口,进一步封装CRUD采用get查询单行remove 删除List查询集合page 分页前缀命名方式区分Mapper层避免混淆,
●泛型T为任意实体对象
●建议如果存在自定义通用Service方法的可能,请创建自己的IBaseService 继承Mybatis-PIus提供的基类
a>IService
MyBatis-Plus中有一个接口 IService和其实现类 ServiceImpl,封装了常见的业务层逻辑详情查看源码IService和ServiceImpl
b>创建Service接口和实现类
public interface UserService extends IService<User> {
}
/*
* 自动注册到Spring容器
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
c>测试查询记录数
@Test
public void ss(){
System.out.println("记录数量是+"+userService.count());
}
d>测试批量插入
@Test
public void insert(){
List<User> list = new ArrayList<>();
for (int i=1;i<30;i++){
String name="小明"+i;
Integer age=10+i;
User user=new User(name, age, "cds");
list.add(user);
}
System.out.println(userService.saveBatch(list));
}
四、常用注解
1、@TableName
经过以上的测试,在使用MyBatis-Plus实现基本的CRUD时, 我们并没有指定要操作的表,只是在
Mapper接口继承BaseMapper时,设置了泛型User,而操作的表为user表,由此得出结论MyBatis-Plus在确定操作的表时,由BaseMapper的泛型决定,即实体类型决定,且默认操作的表名和实体类型的类名一致。若实体类类型的类名和要操作的表的表名不一致,就需要添加注解。
@TableName("User")
public class User {
@TableId
private Long id;
private String name;
private Integer age;
private String email;
private Integer sex;
}
a>通过全局配置解决问题(固定的前缀)
# 配置 MyBatis-Plus 操作表的默认前缀table-prefix : t_
2、@TableId
a>@TableId的value属性
b>@TableId的type属性
配置全局主键策略
db-config :# 配置 MyBatis-Plus 操作表的默认前缀table-prefix : t_# 配置 MyBatis-Plus 的主键策略id-type : auto
3、@TableField
在MP中通过@TableField注解可以指定字段的一些属性,常常解决的问题有两个:
1.对象中的属性名和表中的字段名不一致(非驼峰)
2.对象中的属性字段在表中不存在
4、@TableLogic
a>逻辑删除
b>实现逻辑删除
@TableName("User")
public class User {
@TableId
private Long id;
private String name;
private Integer age;
private String email;
@TableLogic
private Integer sex;
}
五、条件构造器和常用接口
1、wapper介绍
2、QueryWrapper
a>例1:组装查询条件
@Test
public void test01(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",9,30).isNotNull("email");
usermapper.selectList(wrapper).forEach(System.out::println);
}
b>例2:组装排序条件
@Test
public void test02(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByAsc("uid").orderByAsc("age");
usermapper.selectList(queryWrapper).forEach(System.out::println);
}
c>例3:组装删除条件
@Test
public void test03(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,50);
System.out.println(usermapper.delete(wrapper));
}
d>例4:条件的优先级
// 将年龄大于50,或者email是cds的数据的用户名修改为00
@Test
public void test04(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",50).or().eq("email","cds");
User user = new User();
user.setName("00");
user.setAge(99);
System.out.println(usermapper.update(user,queryWrapper));
}
e>例5:组装select子句
@Test
public void test06(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("age","name");
usermapper.selectList(queryWrapper).forEach(System.out::println);
}
f>例6:实现子查询
@Test
public void test07(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.inSql("uid","select uid from user where age<=50");
usermapper.selectList(queryWrapper).forEach(System.out::println);
}
3、updatewrapper
第一种:
将需要更新的字段,设置到entity 中
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("name","shimin");
User user = new User();
user.setAge(18);
第二种:
可以将entity设置为 null ,将需要更新的字段设置到 UpdateWrapper 中
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.set("id","123")eq("name","shimin");
Integer rows = userMapper.update(null, updateWrapper);
4、LambdaQueryWrapper
lambdaQueryWrapper中常用方法
5、LambdaUpdateWrapper
六、插件
1、分页插件
a>添加配置类
@MapperScan("com.at.mybatisplus1.mybatisplus1.mapper")
@Configuration
public class mybatisPlus{
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//数据库类型是MySql,因此参数填写DbType.MYSQL
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//添加乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
b>测试类
@Test
public void test01(){
//设置分页参数
Page<User> page = new Page<>(1, 5);
userMapper.selectPage(page, null);
//获取分页数据
List<User> list = page.getRecords();
list.forEach(System.out::println);
System.out.println("当前页:"+page.getCurrent());
System.out.println("每页显示的条数:"+page.getSize());
System.out.println("总记录数:"+page.getTotal());
System.out.println("总页数:"+page.getPages());
System.out.println("是否有上一页:"+page.hasPrevious());
System.out.println("是否有下一页:"+page.hasNext());
}
2、乐观锁
a>场景
一件商品,成本价是80元,售价是100元。老板先是通知小李,说你去把商品价格增加50元。小
李正在玩游戏,耽搁了一个小时。正好一个小时后,老板觉得商品价格增加到150元,价格太
高,可能会影响销量。又通知小王,你把商品价格降低30元。
此时,小李和小王同时操作商品后台系统。小李操作的时候,系统先取出商品价格100元;小王
也在操作,取出的商品价格也是100元。小李将价格加了50元,并将100+50=150元存入了数据
库;小王将商品减了30元,并将100-30=70元存入了数据库。是的,如果没有锁,小李的操作就
完全被小王的覆盖了。
现在商品价格是70元,比成本价低10元。几分钟后,这个商品很快出售了1千多件商品,老板亏1
万多
b>乐观锁与悲观锁
上面的故事,如果是乐观锁,小王保存价格前,会检查下价格是否被人修改过了。如果被修改过 了,则重新取出的被修改后的价格,150元,这样他会将120元存入数据库。 如果是悲观锁,小李取出数据后,小王只能等小李操作完之后,才能对价格进行操作,也会保证最终的价格是120元。
c>模拟修改冲突
数据库中增加商品表
CREATE TABLE t_product
( id BIGINT(20) NOT NULL COMMENT '主键ID', NAME VARCHAR(30)
NULL DEFAULT NULL COMMENT '商品名称', price INT(11)
DEFAULT 0 COMMENT '价格', VERSION INT(11)
DEFAULT 0 COMMENT '乐观锁版本号', PRIMARY KEY (id) );
添加数据
INSERT INTO t_product (id, NAME, price) VALUES (1, '外星人笔记本', 100);
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("t_product")
public class Product {
private Long id;
private String name;
private Integer price;
private Integer version;
}
@Repository
public interface ProductMapper extends BaseMapper<Product> {}
@Test
public void test01(){
Product product = productMapper.selectById(1);
System.out.println("小李+"+product.getPrice());
Product product1 = productMapper.selectById(1);
System.out.println("小王+"+product1.getPrice());
product.setPrice(product.getPrice()+50);
productMapper.updateById(product);
product1.setPrice(product1.getPrice()-30);
productMapper.updateById(product1);
System.out.println("老班查询的价格是+"+productMapper.selectById(1).getPrice());
}
d>乐观锁实现流程
SELECT id,`name`,price,`version` FROM product WHERE id= 1
更新时,version + 1,如果where语句中的version版本不对,则更新失败
UPDATE product SET price=price+50, `version`=`version` + 1 WHERE id=1 AND
`version`= 1
e>Mybatis-Plus实现乐观锁
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("t_product")
public class Product {
private Long id;
private String name;
private Integer price;
@Version//标识乐观锁版本号字段
private Integer version;
}
@MapperScan("com.at.mybatisplus1.mybatisplus1.mapper")
@Configuration
public class mybatisPlus{
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//数据库类型是MySql,因此参数填写DbType.MYSQL
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//添加乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
SELECT id,name,price,version FROM t_product WHERE id=?
小王查询商品信息:
SELECT id,name,price,version FROM t_product WHERE id=?
小李修改商品价格,自动将version+1
UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
Parameters: 外星人笔记本(String), 150(Integer), 1(Integer), 1(Long), 0(Integer)
小王修改商品价格,此时version已更新,条件不成立,修改失败
UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
Parameters: 外星人笔记本(String), 70(Integer), 1(Integer), 1(Long), 0(Integer)
最终,小王修改失败,查询价格:150
SELECT id,name,price,version FROM t_product WHERE id=?
@Autowired
private ProductMapper productMapper;
@Test
public void test01(){
Product product = productMapper.selectById(1);
System.out.println("小李+"+product.getPrice());
Product product1 = productMapper.selectById(1);
System.out.println("小王+"+product1.getPrice());
product.setPrice(product.getPrice()+50);
productMapper.updateById(product);
product1.setPrice(product1.getPrice()-30);
int result= productMapper.updateById(product1);
if (result==0){
Product product2 = productMapper.selectById(1);
product2.setPrice(product2.getPrice()-30);
productMapper.updateById(product2);
}
System.out.println("老班查询的价格是+"+productMapper.selectById(1).getPrice());
}
七、MyBatisX插件
MybatisX 是一款基于 IDEA 的快速开发插件,为效率而生。
安装方法:打开 IDEA,进入 File -> Settings -> Plugins -> Browse Repositories,输入 mybatisx
搜索并安装。
生成代码(需先在 idea 配置 Database 配置数据源)
重置模板
自定义模板内容
字段信息
配置信息