MyBatis增强器——Mybatis-Plus

  • 一、Mybatis-Plus简介
    • 1.简介
    • 2.特性
    • 3.支持数据库
    • 4.框架结构
  • 二、入门案例
    • 1.开发环境
    • 2.创建数据库及表
      • 创建表
      • 添加数据
    • 3.创建SpringBoot工程
    • 4.编写代码
  • 三、基本crud
  • 四、常用注解
    • 1.@TableName
      • 通过@TableName解决问题
      • 通过全局配置解决问题
    • 2.@TableId
      • 通过@TableId解决问题
      • @TableId的value属性
      • @TableId的type属性
    • 3.@TableField
    • 4.@TableLogic
      • 逻辑删除
  • 五、条件构造函数和常用接口
    • 1.wapper介绍
    • 2.QueryWrapper
    • 3.**UpdateWrapper**
    • 4、condition
    • 5、LambdaQueryWrapper
    • 6、LambdaUpdateWrapper
  • 六、插件
    • 1.分页插件
    • 2.xml自定义分页
    • 3.乐观锁
      • a>场景
      • b>乐观锁与悲观锁
      • c>模拟修改冲突
      • d>乐观锁实现流程
      • e>Mybatis-Plus实现乐观锁
  • 七、通用枚举
  • 八、代码生成器
  • 九、多数据源
  • 十、MybatisX插件

一、Mybatis-Plus简介

1.简介

MyBatis-Plus(简称 MP)是一个 MyBatis的增强工具**,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生**。

2.特性

无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑

损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作

强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分

CRUD 操作,更有强大的条件构造器,满足各类使用需求

支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错

支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由

配置,完美解决主键问题

支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强

大的 CRUD 操作

支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )

内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用

内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询

分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库

内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询

内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

3.支持数据库

任何能使用MyBatis进行 CRUD, 并且支持标准 SQL 的数据库,具体支持情况如下

MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb

达梦数据库,虚谷数据库,人大金仓数据库,南大通用(华库)数据库,南大通用数据库,神通数据库,瀚高数据库

4.框架结构

二、入门案例

1.开发环境

IDE:idea 2019.2

JDK:JDK8+

构建工具:maven 3.5.4

MySQL版本:MySQL 5.7

Spring Boot:2.6.3

MyBatis-Plus:3.5.1

2.创建数据库及表

创建表
CREATE DATABASE `mybatis_plus` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
use `mybatis_plus`;
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;
添加数据
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.创建SpringBoot工程

​ 使用 Spring Initializr快速初始化一个SpringBoot工程

​ 引入依赖

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></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.5.1</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope> </dependency></dependencies>

4.编写代码

配置application.yml

spring:#配置数据源信息datasource:
#    配置数据源类型type: com.zaxxer.hikari.HikariDataSource#    配置连接数据库信息driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSl=falseusername: rootpassword: 123456
注意连接地址urlMySQL5.7版本的url:
jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=falseMySQL8.0版本的url:
jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false否则运行测试用例报告如下错误:
java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more

启动类

在Spring Boot启动类中添加@MapperScan注解,扫描mapper包

@SpringBootApplication
//扫描mapper接口所在的包
@MapperScan("com.mybatisplus.mapper")
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

添加实体

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {private Long id;private String name;private Integer age;private String email;
}

添加mapper

BaseMapper是Mybatis-plus提供的模板mapper,其中包含了基本的CRUD方法,泛型为操作的实体类型

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

测试

@SpringBootTest
public class MybatisPlusTest { @Autowired private UserMapper userMapper; @Test public void testSelectList(){ //selectList()根据MP内置的条件构造器查询一个list集合,null表示没有条      //件,即查询所有                  userMapper.selectList(null).forEach(System.out::println); }
}

注意:

IDEA在userMapper处报错,因为找不到注入的对象,因为类是动态创建的,但是程序可以正确的执行,为了避免报错,可以在mapper接口上添加@Respository、

添加日志

在application.yml中配置日志输出

# 配置MyBatis日志
mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

三、基本crud

1.BaseMapper

​ Mybatis-plus中的基本CRUD在内置的BaseMapper中都已经得到了实现,我们可以直接使用

2.插入

@SpringBootTest
public class MybatisPlusTest {@Testpublic void testInsert(){User user = new User(null,"王世超",23,"shichao@qq.com");int result = userMapper.insert(user);System.out.println("受影响行数"+result);System.out.println("id自动获取"+user.getId());}}

3.删除

​ 通过id删除记录

@Test
public void testDeleteById(){ //通过id删除用户信息 //DELETE FROM user WHERE id=? int result =         userMapper.deleteById(1475754982694199298L);    System.out.println("受影响行数:"+result);
}

4.修改

@Test
public void testUpdateById(){
User user = new User(4L, "admin", 22, null); //UPDATE user SET name=?, age=? WHERE id=? int result = userMapper.updateById(user); System.out.println("受影响行数:"+result);
}

5.查询

@Test
public void testSelectById(){ //根据id查询用户信息//SELECT id,name,age,email FROM user WHERE id=? User user = userMapper.selectById(4L); System.out.println(user); }

6.通用Service

说明:
通用 Service CRUD 封装IService接口,进一步封装 CRUD 采用 get 查询单行 remove 删除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆,
泛型 T 为任意实体对象
建议如果存在自定义通用 Service 方法的可能,请创建自己的 IBaseService 继承
Mybatis-Plus 提供的基类
官网地址:https://baomidou.com/pages/49cc81/#service-crud-%E6%8E%A5%E5%8F%A3

a>IService

MyBatis-Plus中有一个接口 IService和其实现类 ServiceImpl,封装了常见的业务层逻辑,详情查看源码IService和ServiceImpl

b>创建Service接口和实现类

/*** UserService继承IService模板提供的基础功能*/
public interface UserService extends IService<User> {}/*** ServiceImpl实现了IService,提供了IService中基础功能的实现 * 若ServiceImpl无法满足业务需求,则可以使用自定的UserService定义方法,并在实现类中实现 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{}

四、常用注解

1.@TableName

经过以上的测试,在使用MyBatis-Plus实现基本的CRUD时,我们并没有指定要操作的表,只是在Mapper接口继承BaseMapper时,设置了泛型User,而操作的表为user表
由此得出结论,MyBatis-Plus在确定操作的表时,由BaseMapper的泛型决定,即实体类型决定,且默认操作的表名和实体类型的类名一致

提出问题若实体类型的类名和要操作的表的表名不一致,会出现什么问题?

程序抛出异常,Table ‘mybatis_plus.user’ doesn’t exist,因为现在的表名为t_user,而默认操作的表名和实体类型的类名一致,即user表

通过@TableName解决问题

只需要在实体类上添加@TableName(“t_user”),标识实体类对应的表,即可成功执行SQL语句

@TableName("t_user")
public class User {private Long id;private String name;private Integer age;private String email;
}
通过全局配置解决问题

在开发的过程中,我们经常遇到以上的问题,即实体类所对应的表都拥有固定的前缀,例如t_或tbl_此时,可以使用MyBatis-Plus提供的全局配置,为实体类所对应的表名设置默认的前缀,那么就不需要在每个实体类上通过@TableName标识实体类对应的表

mybatis-plus: configuration: # 配置MyBatis日志 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl global-config: db-config: # 配置MyBatis-Plus操作表的默认前缀 table-prefix: t_

2.@TableId

经过以上的测试,MyBatis-Plus在实现CRUD时,会默认将id作为主键列,并在插入数据时,默认基于雪花算法的策略生成id

提出问题若实体类和表中表示主键的不是id,而是其它字段,例如uid,Mybatis-Plus会自动识别uid为主键列吗?我们实体类中的属性id改为uid,将表中的字段id也改为uid,测试添加功能

这时候程序抛出异常,Field ‘uid’ doesn’t have a default value,说明MyBatis-Plus没有将uid作为主键赋值

通过@TableId解决问题

在实体类中uid属性上通过@TableId将其标识为主键,即可成功执行SQL语句

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("t_user")
public class User {@TableIdprivate Long uid;private String name;private Integer age;private String email;
}
@TableId的value属性

若实体类中对应的属性为id,而表中表示主键的字段为uid,此时若只在属性id上添加注解@TableId,则抛出异常Unknown column ‘id’ in ‘field list’,即MyBatis-Plus仍然会将id作为表的主键操作,而表中表示主键的是字段uid

此时需要通过过@TableId注解的value属性,指定表中的主键字段,@TableId(“uid”)或@TableId(value=“uid”)

@TableName("t_user")
public class User {@TableId(value = "uid")private Long id;private String name;private Integer age;private String email;
}
@TableId的type属性

type属性用来定义主键策略

常用的主键策略:

描述
IdType.ASSIGN_ID(默认) 基于雪花算法的策略生成数据id,与数据库id是否设置自增无关
IdType.AUTO 使用数据库的自增策略,注意,该类型请确保数据库设置了id自增,

配置全局主键策略:

mybatis-plus: configuration: # 配置MyBatis日志 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl global-config: db-config: # 配置MyBatis-Plus操作表的默认前缀 table-prefix: t_ # 配置MyBatis-Plus的主键策略 id-type: auto

3.@TableField

经过以上的测试,我们可以发现,MyBatis-Plus在执行SQL语句时,要保证实体类中的属性名和表中的字段名一致,如果实体类中的属性名和字段名不一致的情况,会出现什么问题呢?

情况1

若实体类中的属性使用的是驼峰命名风格,而表中的字段使用的是下划线命名风格

例如实体类属性userName,表中字段user_name

此时MyBatis-Plus会自动将下划线命名风格转化为驼峰命名风格

相当于在MyBatis中配置

情况2

若实体类中的属性和表中的字段不满足情况1

例如实体类属性name,表中字段username

此时需要在实体类属性上使用@TableField(“username”)设置属性所对应的字段名

@TableName("t_user")
public class User {@TableId(value = "uid")private Long id;@TableField("username")private String name;private Integer age;private String email;
}

4.@TableLogic

逻辑删除

​ 物理删除:真实删除,将对应的数据从数据库删除,之后查询不到此条被删除的数据

​ 逻辑删除:假删除,将对应数据中代表是否被删除字段的状态修改为“被删除状态”,之后在 数据库中仍旧看到此条数据记录

​ 使用场景:可以进行数据恢复

@TableName("t_user")
public class User {@TableId(value = "uid")private Long id;@TableField("username")private String name;private Integer age;private String email;@TableLogicprivate Integer isDeleted;
}

测试

测试删除功能,真正执行的是修改
UPDATE t_user SET is_deleted=1 WHERE id=? AND is_deleted=0测试查询功能,被逻辑删除的数据默认不会被查询
SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0

五、条件构造函数和常用接口

1.wapper介绍

Wrapper : 条件构造抽象类,最顶端父类

​ AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件

​ QueryWrapper : 查询条件封装

​ UpdateWrapper : Update 条件封装

​ AbstractLambdaWrapper : 使用Lambda 语法

​ LambdaQueryWrapper :用于Lambda语法使用的查询Wrapper

​ LambdaUpdateWrapper : Lambda 更新封装Wrapper

2.QueryWrapper

​ a.组装查询条件

@Testpublic void test01(){//     查询条件包含a 年龄在20到30之间,并且邮箱不为null的用户信息//SELECT id,username AS name,age,email,is_deleted FROM t_user// WHERE is_deleted=0 AND (username LIKE ?// AND age BETWEEN ? AND ? AND email IS NOT NULL)QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.like("username","张").between("age",20,30).isNotNull("email");List<User> lists = userMapper.selectList(wrapper);lists.forEach(System.out::println);}

​ b.组装排序条件

 @Testpublic void test02(){QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.orderByDesc("age").orderByAsc("uid");List<User> users = userMapper.selectList(queryWrapper);users.forEach(System.out::println);}

​ c.组装删除条件

 @Testpublic void test03(){//        删除email为空的用户//DELETE FROM t_user WHERE (email IS NULL)QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.isNull("email");
//        条件构造器也可以构建删除语句的条件int delete = userMapper.delete(queryWrapper);System.out.println("受影响的行数"+delete);}

​ d.条件的优先级

@Testpublic void  test04(){QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.like("username","a").gt("age",20).or().isNull("email");User user = new User();user.setAge(18);user.setEmail("user@liu.com");int update = userMapper.update(user, queryWrapper);System.out.println("受影响的行数"+update);}
@Testpublic void  test041(){QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.like("username","a").and(i -> i.gt("age",20).or().isNull("email"));User user = new User();user.setAge(18);user.setEmail("user@liu.com");int update = userMapper.update(user, queryWrapper);System.out.println("受影响的行数"+update);}

​ e.组装select子句

@Testpublic void test05(){//        查询用户信息的username和age字段QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.select("username","age");List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);maps.forEach(System.out::println);}

​ f.实现子查询

@Testpublic void  test06(){QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.inSql("id","select id from t_user where id <= 3");List<User> list = userMapper.selectList(queryWrapper);list.forEach(System.out::println);}

3.UpdateWrapper

 @Testpublic void test07(){UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
//        将(年龄大于20或邮箱为null)并且用户中包含有a的用户信息修改
//        组装set子句以及修改条件
//        lambda表达式内的逻辑优先运算updateWrapper.set("age",18).set("email","user@atguigu.com").like("username","a").and(i -> i.gt("age",20).or().isNull("email"));
//        这里必须要创建user对象,否则无法应用自动填充,如果没有自动填充,可以设置为nullint update = userMapper.update(null, updateWrapper);System.out.println(update);}

4、condition

在真正的开发过程中,组装条件是常见的功能,而这些条件数据来源与用户输入,是可选的,因此我们在组装这些条件时,必须先判断用户是否选择了这些条件,若选择则需要组装这些条件,若没有选择则一定不能组装,以免影响SQL执行的结果

    @Testpublic void test08(){//        定义查询条件,有可能为空 (用户未输入或未选择)String username = null;Integer ageBegin = 10;Integer ageEnd = 24;QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        Stringutils.isNotBlank判断某字符串是否不为空且长度不为0且不由空白符(whitespace)构成if (StringUtils.isBlank(username)){queryWrapper.like("username","a");}if (ageBegin != null){queryWrapper.ge("age",ageBegin);}if (ageEnd != null){queryWrapper.le("age",ageEnd);}
//        select id,username as name,age,email,is_deleted from t_user where(age >= ? AND age<= ?)List<User> users = userMapper.selectList(queryWrapper);users.forEach(System.out::println);}
 @Testpublic void test081(){//        定义查询条件,有可能为null(用户魏输入或未选择)String username = null;Integer ageBegin = 10;Integer ageEnd = 24;QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.like(StringUtils.isNotBlank(username),"username","张").ge(ageBegin != null,"age",ageBegin).le(ageEnd != null,"age",ageEnd);//SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE (age >= ? AND age <= ?)List<User> users = userMapper.selectList(queryWrapper);users.forEach(System.out::println);}

5、LambdaQueryWrapper

@Test
public void test09() { //定义查询条件,有可能为null(用户未输入) String username = "a"; Integer ageBegin = 10; Integer ageEnd = 24; LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(); //避免使用字符串表示字段,防止运行时错误 queryWrapper .like(StringUtils.isNotBlank(username), User::getName, username)         .ge(ageBegin != null, User::getAge, ageBegin) .le(ageEnd != null, User::getAge, ageEnd); List<User> users = userMapper.selectList(queryWrapper); users.forEach(System.out::println); }

6、LambdaUpdateWrapper

@Test public void test10() { //组装set子句 LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>(); updateWrapper .set(User::getAge, 18) .set(User::getEmail, "user@atguigu.com") .like(User::getName, "a") .and(i -> i.lt(User::getAge, 24).or().isNull(User::getEmail)); //lambda 表达式内的逻辑优先运算 User user = new User(); int result = userMapper.update(user, updateWrapper);                   System.out.println("受影响的行数:" + result);
}

六、插件

1.分页插件

​ a添加配置类

@Configuration
@MapperScan("com.mybatisplus.mapper")
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}
}
b测试
   @Testpublic void testPage(){//        设置分页参数Page<User> page = new Page<>(2, 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.xml自定义分页

​ a.UserMapper中定义接口方法

/*** 根据年龄查询用户列表,分页显示* @param page 分页对象 xml中可以从里面进行取值,传递参数PAGE即自动分页,必须放在第一位* @param age 年龄* @return*/Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age);

b>UserMapper.xml中编写SQL

<!--    Page<User> selectPageVo(@Param("page") Page<User> page,-->
<!--    @Param("age") Integer age);--><select id="selectPageVo" resultType="User">select uid,username,age,email from t_user where age > #{age}</select>

c>测试

@Testpublic void testPage(){//        设置分页参数Page<User> page = new Page<>(1, 5);userMapper.selectPageVo(page,20);
//         获取分页数据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());}

3.乐观锁

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;
}

添加mapper

@Mapper
public interface ProductMapper extends BaseMapper<Product> {}

测试

@Testpublic void testConUpdate(){//        1.小李Product p1 = productMapper.selectById(1L);System.out.println("小李取出的价格"+p1.getPrice());//        2.小王Product p2 = productMapper.selectById(1L);System.out.println("小王取出的价格"+p2.getPrice());//        3.小李价格加了50元,存入了数据库p1.setPrice(p1.getPrice()+50);int update = productMapper.updateById(p1);System.out.println("小李修改的结果"+update);//        4.小娃昂将商品减了元,存入数据库p2.setPrice(p2.getPrice()-30);int result = productMapper.updateById(p2);System.out.println("小王修改的结果"+result);//        最后的结果Product p3 = productMapper.selectById(1L);System.out.println("最后的结果魏"+p3);}
d>乐观锁实现流程

数据库中添加version字段

取出记录时,获取当前version

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;@Versionprivate Integer version;
}

添加乐观锁配置

@Configuration
@MapperScan("com.mybatisplus.mapper")
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();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)
最终,小王修改失败,查询价格:150SELECT id,name,price,version FROM t_product WHERE id=?

优化流程

    @Testpublic void testConUpdate(){//        1.小李Product p1 = productMapper.selectById(1L);System.out.println("小李取出的价格"+p1.getPrice());//        2.小王Product p2 = productMapper.selectById(1L);System.out.println("小王取出的价格"+p2.getPrice());//        3.小李价格加了50元,存入了数据库p1.setPrice(p1.getPrice()+50);int update = productMapper.updateById(p1);System.out.println("小李修改的结果"+update);//        4.小娃昂将商品减了元,存入数据库p2.setPrice(p2.getPrice()-30);int result = productMapper.updateById(p2);System.out.println("小王修改的结果"+result);if (result == 0){p2=productMapper.selectById(1L);p2.setPrice(p2.getPrice()-30);result = productMapper.updateById(p2);}System.out.println("小王修改重试的结果"+result);//        最后的结果Product p3 = productMapper.selectById(1L);System.out.println("最后的结果魏"+p3);}

七、通用枚举

表中的有些字段值是固定的,例如性别(男或女),此时我们可以使用Mybatis-Plus的通用美剧来实现

1.数据库添加字段sex

2.创建通用枚举类型

@Getter
public enum SexEnum {MALE(1,"男"),FEMALE(2,"女");@EnumValueprivate Integer sex;private String sexName;SexEnum(Integer sex, String sexName) {this.sex = sex;this.sexName = sexName;}
}

3.配置扫描通用枚举

mybatis-plus:configuration:
#    配置Mybatis日志log-impl: org.apache.ibatis.logging.stdout.StdOutImplglobal-config:db-config:#        配置Mybatis-plus操作表的默认前缀table-prefix: t_#      配置Mybatis-plus的主键策略
#      id-type: auto
#  配置扫描通用枚举type-enums-package: com.mybatisplus.enums
#  配置类型别名所对应的包type-aliases-package: com.mybatisplus.pojo

4.测试

 @Testpublic void test01(){User user = new User();user.setName("Enum");user.setAge(20);
//        设置性别信息为枚举项,会将@EnumValue注解所标识的属性值存储到数据库user.setSex(SexEnum.MALE);//INSERT INTO t_user ( username, age, sex ) VALUES ( ?, ?, ? )// Parameters: Enum(String), 20(Integer), 1(Integer)userMapper.insert(user);}

八、代码生成器

1.引入依赖

     <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.1</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.31</version></dependency>

2.快速生成

public class Test03 {public static void main(String[] args) {FastAutoGenerator.create("jdbc:mysql://127.0.0.1:3306/mybatis_plus? characterEncoding=utf-8&userSSL=false", "root", "123456").globalConfig(builder -> {builder.author("mybatisplus") //设置作者.fileOverride() //覆盖已经生成的文件.outputDir("D://mybatis_plus");//指定输出目录}).packageConfig(builder -> {builder.parent("com.mybatisplus")//设置父包名.moduleName("mybatisplus")//设置父包模块名.pathInfo((Collections.singletonMap(OutputFile.mapperXml, "D://mybatis_plus")));
//                            设置mapperXml生成路径}).strategyConfig(builder -> {builder.addInclude("t_user")//设置需要生成的表名.addTablePrefix("t_","c_");//设置前缀}).templateEngine(new FreemarkerTemplateEngine()).execute(); //使用Freemarker引擎模板,默认的是velocity引擎模板)}
}

九、多数据源

适用于多种场景:纯粹多库、 读写分离、 一主多从、 混合模式等

目前我们就来模拟一个纯粹多库的一个场景,其他场景类似

场景说明:

我们创建两个库,分别为:mybatis_plus(以前的库不动)与mybatis_plus_1(新建),将

mybatis_plus库的product表移动到mybatis_plus_1库,这样每个库一张表,通过一个测试用例

分别获取用户数据与商品数据,如果获取到说明多库模拟成功

1.创建数据库及表

CREATE DATABASE `mybatis_plus_1` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
use `mybatis_plus_1`;
CREATE TABLE 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 product (id, NAME, price) VALUES (1, '外星人笔记本', 100);删除mybatis_plus库product表
use mybatis_plus; DROP TABLE IF EXISTS product;

2.引入依赖

<dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId>   <version>3.5.0</version>
</dependency>

3.配置多数据源

spring:
#  配置数据源信息datasource:dynamic:
#      设置默认的数据源或者数据源组,默认值即为masterprimary:
#      严格匹配数据源,默认false true 未匹配到指定数据时抛异常,false使用默认数据源strict: falsedatasource:master :url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=falsedriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 123456slave_1:url: jdbc:mysql://localhost:3306/mybatis_plus_1?characterEncoding=utf-8&useSSL=falsedriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 123456

4.创建用户service

public interface UserService extends IService<User> {}
@DS("master")
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{}

5.创建商品service

public interface ProductService extends IService<Product> { }
@DS("slave_1")
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService { }

6.测试

@Autowiredprivate UserService userService;@Autowiredprivate ProductService productService;@Testpublic void testDataSource(){System.out.println(userService.getById(1L));System.out.println(productService.getById(1L));}

十、MybatisX插件

MyBatis-Plus为我们提供了强大的mapper和service模板,能够大大的提高开发效率

但是在真正开发过程中,MyBatis-Plus并不能为我们解决所有问题,例如一些复杂的SQL,多表

联查,我们就需要自己去编写代码和SQL语句,我们该如何快速的解决这个问题呢,这个时候可

以使用MyBatisX插件

MyBatisX一款基于 IDEA 的快速开发插件,为效率而生。

插件用法:http://baomidou.com/pages/ba5b24/

MyBatis增强器——Mybatis-Plus相关推荐

  1. (Mybatis)Mybatis简介和初步使用

    1. Mybatis简介 1.1什么是Mybatis MyBatis 是一款优秀的持久层框架 它支持定制化 SQL.存储过程以及高级映射. MyBatis 避免了几乎所有的 JDBC 代码和手动设置参 ...

  2. MyBatis(三)MyBatis缓存和工作原理

    MyBatis缓存 MyBatis提供了一级缓存和二级缓存,并且预留了集成第三方缓存的接口. 从上面MyBatis的包结构可以很容易看出跟缓存相关的类都在cache的package里,其底层是一个Ca ...

  3. MyBatis(一)MyBatis介绍和配置详解

    在Java程序里面去操作数据库,最原始的办法是使用JDBC的API.需要分为六步: 注册驱动 通过DriverManager获取一个Connection 通过Connection创建一个Stateme ...

  4. MyBatis(二)MyBatis基本流程源码分析

    MyBatis体系结构 MyBatis的工作流程 在MyBatis启动的时候我们要去解析配置文件,包括全局配置文件和映射器配置文件,我们会把它们解析成一个Configuration对象,里面会包含各种 ...

  5. 【MyBatis】MyBatis初体验

    文章目录 框架 软件开发三层结构 MyBatis概念 MyBatis由来 ORM框架与MyBatis的区别 MyBatis编码流程 框架 是一个可以重复使用的设计构件,我们在做开发的时候框架是直接调来 ...

  6. MyBatis】MyBatis一级缓存和二级缓存

    转载自  MyBatis]MyBatis一级缓存和二级缓存 MyBatis自带的缓存有一级缓存和二级缓存 一级缓存 Mybatis的一级缓存是指Session缓存.一级缓存的作用域默认是一个SqlSe ...

  7. mybatis传递多个参数_深入浅出MyBatis:MyBatis解析和运行原理

    原文:https://juejin.im/post/5abcbd946fb9a028d1412efc 本篇文章是「深入浅出MyBatis:技术原理与实践」书籍的总结笔记. 上一篇介绍了反射和动态代理基 ...

  8. mybatis支持驼峰自动转换sql吗_SpringBoot整合mybatis——配置mybatis驼峰命名规则自动转换...

    一.简述 mybatis驼峰式命名规则自动转换: 使用前提:数据库表设计按照规范"字段名中各单词使用下划线"_"划分": 使用好处:省去mapper.xml文件 ...

  9. MyBatis系列-Mybatis入门精讲

    导语   在之前的分享中没有做过关于Mybatis内容相关的分享,这段时间深入的学习了关于Mybatis的相关知识,这里首先来对Mybatis的相关基础知识做一个介绍,这个系列的分享博主会做到有始有终 ...

最新文章

  1. Django博客系统注册(图形验证码接口设计和定义)
  2. 网络安全中的AI:2021年的六个注意事项
  3. 转:csdn怎么快速转载别人的文章
  4. PHP源码安装及配置——以fastCGI的方式与httpd整合
  5. 什么可以搜python答案_超星Python程序设计答案章节测试答案免费,能搜索网课答案的公众号...
  6. CVX 几何规划 两个官网样例
  7. 【 58沈剑 架构师之路】4种事务的隔离级别,InnoDB如何巧妙实现?
  8. 自定义Xshell高亮
  9. 织梦cms仿站_文章发布出现WTS-WAF页面
  10. 解析XML文档之一:使用SAX解析
  11. CUDA实现focal_loss
  12. 我只会SQL,到底能不能找到工作?
  13. 深造分布式 打败面试官 招式三 直捣黄龙
  14. ArrayList和LinkedList时间、空间复杂度对比
  15. 2023二建建筑施工备考第二天Day06水泥
  16. 高等组合学笔记(三): 间隔排列,投票问题,圈集排列组合与生成函数简介
  17. Macbook ssh免密登录
  18. 数字图像处理(1)-采样,量化,空间分辨率,灰度级分辨率
  19. Python_阿里云物联网_数据/图像/音频传输
  20. Pinyin4j 详解及使用

热门文章

  1. 关于xx集团公司对驰骋bpm,jflow工作流系统若干问题及其答复
  2. Python活动报名表的分析、处理和筛选
  3. JVM(三)GC垃圾回收以及四种GC算法
  4. (六)从零开始学人工智能-搜索:对抗搜索
  5. LCD1602液晶显示屏的工作原理图是什么呢?
  6. SYN 攻击 常识 预防
  7. Python-正则表达式匹配数字
  8. 如何在VUE项目中添加使用LivePlayer.js直播点播H5免费播放器
  9. Mysql 备份恢复与xtrabackup备份
  10. 【ROS学习】(六)ROS多线程订阅消息