ss1 MybatisPlus
1.1 简介
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,简化 CRUD 操作,为简化开发、提高效率而生。
学习文档:https://baomidou.com/pages/24112f/
1.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 操作智能分析阻断,也可自定义拦截规则,预防误操作
1.3 支持数据库
任何能使用
MyBatis
进行 CRUD, 并且支持标准 SQL 的数据库,都能在MP中使用,因为MP只做增强不做修改!
- MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb
- 达梦数据库,虚谷数据库,人大金仓数据库,南大通用(华库)数据库,南大通用数据库,神通数据库,瀚高数据库
1.4 框架结构
2 快速入门
2.1 开发环境
- IDE:IDEA 2020.3
- JDK:JDK8+
- 构建工具:Maven 3.6.1
- MySQL:MySQL 8.0.28
- Spring Boot:2.7.17
- MyBatis-Plus:3.5.4
2.1 设计数据库
1.创建数据库
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;
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.创建简易springboot工程
这里就省略创建过程了...
4.导入所需依赖
mybatis-pluls、mysql、lombok
<dependencies> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency> <!-- mybatis-plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.4</version> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.3.1</version> </dependency> </dependencies>
5.在yml文件中配置连接数据库信息
spring:
datasource:
username: root
password: hsp
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&userSSL=false&serverTimezone=GMT%2B8
mybatis-plus:
configuration:
#配置Mybatis日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
6.在springboot启动类中添加@MapperScan注解扫描mapper文件下的所有接口
package com.heima;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.heima.mapper")
public class SpringbootMybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisplusApplication.class, args);
}
}
7.编写实体类,对应数据库中的字段
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
8.编写UserMapper接口
package com.heima.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* @Author 黑麻哥
* @Date 2023/12/21 11:42
* @Version 1.0
*/
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
这里我们继承了MP中的BaseMapper接口,并且泛型的类型是我们需要操作的实体类的类型,进入到BaseMapper类中我们就可以发现,我们拥有了基本的单表的CRUD功能了
9.测试
在SpringBoot的test包下测试
package com.heima;
import com.heima.mapper.UserMapper;
import com.heima.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author 黑麻哥
* @Date 2023/12/21 11:42
* @Version 1.0
*/
@SpringBootTest
public class UserTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect(){
//通过条件控制符查询list集合,当没有条件时,可以设置参数为null
List<User> list = userMapper.selectList(null);
for (User user : list) {
System.out.println(user);
}
}
}
这样我们就能查询到数据了
3 MP的CRUD
3.1.BaseMapper<T>
- 通用 CRUD 封装BaseMapper 接口,为 Mybatis-Plus 启动时自动解析实体表关系映射转换为 Mybatis 内部对象注入容器
- 泛型 T 为任意实体对象
- 参数 Serializable 为任意类型主键 Mybatis-Plus 不推荐使用复合主键约定每一张表都有自己的唯一 id 主键
- 对象 Wrapper 为条件构造器
上面我们说过,MP的BaseMapper接口已经为我们封装了大量的CRUD方法,因此我们继承后可以直接使用...
3.2 调用Mapper层实现CRUD
使用的案例不使用条件构造器,或者条件构造器为空
3.2.1 增加
@Test
public void testInsert(){
//实现新增用户信息
//INSERT INTO user ( id, age, name, email ) VALUES ( ?, ?, ?, ? )
User user = new User();
user.setEmail("375482471@qq.com");
user.setName("王五");
user.setAge(29);
int result = userMapper.insert(user);
if(result > 0){
System.out.println("insert执行成功...");
}
System.out.println("id:" + user.getId());
}
最终执行的结果,所获取的id为1737734850107961345
这是因为MyBatis-Plus在实现插入数据时,会默认基于雪花算法的策略生成id,生成策略是可变的
3.2.2 删除
1.根据id删除
调用方法:int deleteById(Serializable id);
@Test
public void testDeleteById(){
//实现根据id删除用户信息
//DELETE FROM user WHERE id = ?
int result = userMapper.deleteById(1737734850107961345L);
if(result > 0){
System.out.println("deleteById执行成功...");
}
}
2.根据ID批量删除数据
调用方法:int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
@Test
public void deleteBatchIds(){
//实现根据list传入多个id删除多个用户信息
//DELETE FROM user WHERE id IN ( ? , ? , ? )
List<Long> list = Arrays.asList(5L, 4L, 3L);
int result = userMapper.deleteBatchIds(list);
if(result > 0){
System.out.println("deleteBatchId执行成功...");
}else{
System.out.println("deleteBatchId执行失败...");
}
}
3.根据Map条件删除数据
调用方法:int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
@Test
public void testDeleteByMap(){
//实现根据Map设置条件删除用户信息
//DELETE FROM user WHERE (name = ? AND age = ?)
Map map = new HashMap();
//map中键值对存储字段和条件
map.put("age",18);
map.put("name","黑麻");
int result = userMapper.deleteByMap(map);
if(result > 0){
System.out.println("deleteByMap执行成功...");
}else{
System.out.println("deleteByMap执行失败...");
}
}
利用map的键值对,传入要删除的信息,符合则删除
3.2.3 查询
1.根据单个ID查询单个用户信息
调用方法:T selectById(Serializable id);
@Test
public void select(){
//实现根据id查询用户信息
User user = userMapper.selectById(2L);
System.out.println(user);
}
2.根据多个ID查询多个用户信息
/**
* 根据多个id查询用户数据
*/
@Test
public void testSelectBatchIds(){
//执行SQL为:SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
List<Long> ids = Arrays.asList(1L,2L,3L);
List<User> users = userMapper.selectBatchIds(ids);
users.forEach(System.out::println);
}
3.根据map条件查询用户信息
@Test
public void select(){
//实现map设置条件查询用户信息
//SELECT id,age,name,email FROM user WHERE (name = ? AND age = ?)
Map map = new HashMap();
map.put("name","Tom");
map.put("age","16");
List userList = userMapper.selectByMap(map);
for (Object o : userList) {
System.out.println(o);
}
}
4.查询所有用户信息
@Test
public void select(){
//实现查询所有用户信息
List<User> userList = userMapper.selectList(null);
for (User user : userList) {
System.out.println(user);
}
}
3.2.3 修改
调用方法:int updateById(@Param(Constants.ENTITY) T entity);
@Test
public void updateById(){
//实现根据id修改用户信息
//UPDATE user SET age=?, name=?, email=? WHERE id=?
User user = new User(2L, 18, "黑麻", "123321555@qq,com",0);
int result = userMapper.updateById(user);
if(result > 0){
System.out.println("result执行成功...");
}else{
System.out.println("result执行失败...");
}
}
3.3 IService<T>
说明:
- 通用 Service CRUD 封装IService接口,进一步封装 CRUD 采用 get 查询单行 remove 删除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆,
- 泛型 T 为任意实体对象
- 建议如果存在自定义通用 Service 方法的可能,请创建自己的 IBaseService 继承 Mybatis-Plus 提供的基类
- 对象 Wrapper 为 条件构造器
MyBatis-Plus中有一个接口 **IService**和其实现类 ServiceImpl,封装了常见的业务层逻辑
因此我们在使用的时候仅需在自己定义的**Service接口中继承IService接口,在自己的实现类中实现自己的Service并继承ServiceImpl**即可实现方法
3.4 调用Service层实现CRUD
我们在自己的Service接口中通过继承MyBatis-Plus提供的IService接口,不仅可以获得其提供的CRUD方法,而且还可以使用自身定义的方法。
先在springboot的test包中创建我们的测试类UserServiceTest,注入UserService
3.4.1 查询总记录数
调用方法:int count()
@Test
public void getCount(){
//查询总记录数
//SELECT COUNT(*) FROM user
long count = userService.count();
System.out.println("总记录数:" + count);
}
3.4.2 批量添加数据
调用方法: boolean saveBatch()
@Test
public void InsertBatch(){
//批量添加
//INSERT INTO user ( id, name ) VALUES ( ?, ? )
List list = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
User user = new User();
user.setName("pyy" + i);
list.add(user);
}
boolean result = userService.saveBatch(list);
System.out.println(result);
}
3.4.3 批量删除数据
调用方法: removeByMap()
@Test
public void deleteBatch(){
//批量删除
Map map = new HashMap();
for (int i = 1; i <= 10; i++) {
map.put("name" , "pyy"+i);
userService.removeByMap(map);
}
}
3.5 BaseMapper和Iservice
其实在我们看来,这两个方法都差不多,都为我们提供了CRUD的方法,但是MP的作者为什么会为我们提供两个差不多的操作数据库的接口呢?
说实在的,我们只需要学会使用即可,对于他们的关系,倒是不用太过于深究...但是Mapper接口是没有提供批处理的,而Iservice接口提供了批处理
另外,IService 的默认实现 com.baomidou.mybatisplus.extension.service.impl.ServiceImpl 就是调用 BaseMapper 来操作数据库,所以我猜 IService 是 Java 8 之前对 BaseMapper 所做的扩展,而 Java 8 之后,因为有了 default 方法,ServiceImpl 里面的东西其实都可以移到 BaseMapper 里面了。
4 常用注解
MyBatis-Plus提供的注解可以帮我们解决一些数据库与实体之间相互映射的问题。
4.1 @TableName
在之前我们使用MP实现基本的CRUD时,我们并没有指定要操作的表,只是在Mapper接口继承BaseMapper时,设置了泛型User。同时我们创建的表为user表,由此得出结论,MP在确定操作的表时,由BaseMapper的泛型决定,即实体类型决定,且默认操作的表名和实体类型的类名一致。
4.1.1 引出问题
当我们修改表名为t_user时候,我们再来操作数据库会出现什么问题呢?
我们发现,这里出现了表不存在的报错,但是我们查询的表依然是from user。因此,现在我们可以肯定, 我们默认操作的表是BaseMapper泛型中设定的类型对应的表
4.1.2 解决问题
我们怎么解决要操作的表和数据库的表不一致的问题呢?
1.很简单,MP为我们提供了@TableName注解标识实体类对应的表,即可成功执行SQL语句
@Data
@TableName("t_user")
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
2.我们也可以在yml配置文件中配置信息也可以解决
mybatis-plus:
global-config:
db-config:
# 设置实体类所对应的表的统一前缀
table-prefix: t_
4.2 @TableId
MP在实现CRUD时,会默认将id作为主键列,并在插入数据时,默认基于雪花算法的策略生成id
4.2.1 引出问题
若实体类和表中表示主键的不是id,而是其他字段,例如uid,MP会自动识别uid为主键列吗?
我们将实体类和user表的id字段更改为uid,看看能否正常运行
程序抛出异常,Field ‘uid’ doesn’t have a default value,说明MyBatis-Plus没有将uid
作为主键赋值
4.2.2 解决问题
在实体类中uid属性上通过
@TableId
将其标识为主键,即可成功执行SQL语句
@Date
public class User {
@TableId
private Long uid;
private String name;
private Integer age;
private String email;
}
4.2.3 @TableId中的value属性
若实体类中主键对应的属性为id,而表中的主键为uid与实体类不符,则仍然会报错这时我们需要使用@TableId("uid")或@TableId(value="uid")绑定实体类中的id属性与表中的uid相对应
//将属性所对应的字段指定为主键
//@TableId注解的value属性用于指定主键的字段
@TableId(value = "uid")
private Long uid;
4.2.4 @TableId中的type属性
type属性用来定义主键策略:默认雪花算法
常见的主键策略:
- IdType.ASSIGN_ID(默认)即使用雪花算法,与数据库id是否自增无关
- IdType.AUTO:使用自增策略,使用此类型要确保数据库中该字段设置了自增
方式一:
在@TableId注解中加入type属性
//将属性所对应的字段指定为主键
//@TableId注解的value属性用于指定主键的字段
@TableId(value = "uid", type = IdType.AUTO)
private Long uid;
方式二:
在yml配置文件中配置id策略
mybatis-plus:
global-config:
db-config:
#配置Mybatis-Plus的主键策略
id-type: auto
4.3 @TbaleField
经过以上的测试,我们可以发现,MyBatis-Plus在执行SQL语句时,要保证实体类中的属性名和表中的字段名一致
如果实体类中的属性名和字段名不一致的情况,会出现什么问题呢?
1 情况一
若实体类中的属性使用的是驼峰命名风格,而表中的字段使用的是下划线命名风格
例如实体类属性userName,表中字段user_name
此时MyBatis-Plus会自动将下划线命名风格转化为驼峰命名风格
相当于在MyBatis中配置自动转换
2 情况二
若实体类中的属性和表中的字段不满足情况1
例如实体类属性name,表中字段username
此时需要在实体类属性上使用@TableField("username")设置属性所对应的字段名
public class User {
@TableId("uid")
private Long id;
@TableField("username")
private String name;
private Integer age;
private String email;
}
4.4 @TableLogic
4.4.1 逻辑删除
- 物理删除:真实删除,将对应数据从数据库中删除,之后查询不到此条被删除的数据
- 逻辑删除:假删除,将对应数据中代表是否被删除字段的状态修改为“被删除状态”,之后在数据库中仍旧能看到此条数据记录
使用场景:可以进行数据恢复
4.4.2 实现逻辑删除
数据库中创建逻辑删除状态列,设置默认值为0
实体类中添加逻辑删除属性
实体类中添加逻辑删除属性测试删除功能,真正执行的是修改
public void testDeleteById(){
int result = userMapper.deleteById(1527472864163348482L);
System.out.println(result > 0 ? "删除成功!" : "删除失败!");
System.out.println("受影响的行数为:" + result);
}
实现逻辑删除,将is_deleted设置为1,实际执行的是update语句
-
-
此时执行查询方法,查询的结果为自动添加条件
is_deleted=0
5 条件构造器
5.1 Wrapper介绍
- Wrapper : 条件构造抽象类,最顶端父类
- AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件
- QueryWrapper : 查询条件封装
- UpdateWrapper : Update 条件封装
- AbstractLambdaWrapper : 使用Lambda 语法
- LambdaQueryWrapper :用于Lambda语法使用的查询Wrapper
- LambdaUpdateWrapper : Lambda 更新封装Wrapper
5.2 QueryWrapper
- 组装查询条件
案例说明:
//查询用户名包含a,年龄在20到30之间,邮箱信息不为空的用户信息
这里使用了模糊语句,区间语句,还有判断语句,不使用条件构造器的情况下的MP方法好像实现不了,这时候我们就可以引出Wrapper构造器了...
1.创建QueryWrapper对象,里面封装了一系列的方法,实现条件的构造
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name","a")
.between("age",20,30)
.isNotNull("email");
2.调用userMapper中查询的参数含有条件构造器的方法
List<User> list = userMapper.selectList(queryWrapper);
for (User user : list) {
System.out.println(user );
}
3.完整代码
package com.heima;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.mapper.UserMapper;
import com.heima.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;
import java.util.Map;
/**
* @Author 黑麻哥
* @Date 2023/12/22 13:56
* @Version 1.0
*/
@SpringBootTest
public class UserTestQueryWrapper {
@Autowired
private UserMapper userMapper;
@Test
public void testGet(){
//查询用户名包含a,年龄在20到30之间,邮箱信息不为空的用户信息
//SELECT uid AS id,age,name,email,is_deleted FROM user WHERE is_deleted=0 AND (name LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL)
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name","a")
.between("age",20,30)
.isNotNull("email");
List<User> list = userMapper.selectList(queryWrapper);
for (User user : list) {
System.out.println(user );
}
}
}
- 组装排序条件
案例说明:
查询用户信息,按照年龄的降序排序,若年龄相同,则按照id升序排序
在数据库中我们的操作是ACS升序,DESC降序,同样在Wrapper中也有这样的方法
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("age")
.orderByAsc("uid");
调用userMapper
List<User> userList = userMapper.selectList(queryWrapper);
for (User user : userList) {
System.out.println(user);
}
}
完整代码:
package com.heima;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.mapper.UserMapper;
import com.heima.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;
import java.util.Map;
/**
* @Author 黑麻哥
* @Date 2023/12/22 13:56
* @Version 1.0
*/
@SpringBootTest
public class UserTestQueryWrapper {
@Autowired
private UserMapper userMapper;
@Test
public void getBySort(){
//查询用户信息,按照年龄的降序排序,若年龄相同,则按照id升序排序
//SELECT uid AS id,age,name,email,is_deleted FROM user WHERE is_deleted=0 ORDER BY age DESC,uid ASC
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("age")
.orderByAsc("uid");
List<User> userList = userMapper.selectList(queryWrapper);
for (User user : userList) {
System.out.println(user);
}
}
}
- 组装删除条件
案例说明:
//删除邮箱地址为null的用户信息
这里我们需要判断邮箱地址不为空的判断语句
//删除邮箱地址为null的用户信息
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.isNull("email");
调用userMapper
int result = userMapper.delete(queryWrapper);
if(result > 0){
System.out.println("删除成功...");
}else{
System.out.println("删除失败...");
}
}
完整代码
package com.heima;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.mapper.UserMapper;
import com.heima.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;
import java.util.Map;
/**
* @Author 黑麻哥
* @Date 2023/12/22 13:56
* @Version 1.0
*/
@SpringBootTest
public class UserTestQueryWrapper {
@Autowired
private UserMapper userMapper;
@Test
public void testDel(){
//删除邮箱地址为null的用户信息
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.isNull("email");
int result = userMapper.delete(queryWrapper);
if(result > 0){
System.out.println("删除成功...");
}else{
System.out.println("删除失败...");
}
}
}
- 条件优先级
案例说明一:
//将(年龄大于20并且用户名中包含有a)或邮箱为null的用户信息修改
先实现括号里的语句,再实现后面的或语句
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",20)
.like("name","a")
.or()
.isNull("email");
调用userMapper
int result = userMapper.update(user,queryWrapper);
System.out.println("result:" + result);
完整代码
package com.heima;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.mapper.UserMapper;
import com.heima.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;
import java.util.Map;
/**
* @Author 黑麻哥
* @Date 2023/12/22 13:56
* @Version 1.0
*/
@SpringBootTest
public class UserTestQueryWrapper {
@Autowired
private UserMapper userMapper;
@Test
public void testUpd(){
//将(年龄大于20并且用户名中包含有a)或邮箱为null的用户信息修改
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",20)
.like("name","a")
.or()
.isNull("email");
User user = new User();
user.setName("小明");
user.setEmail("789456@huohu.com");
int result = userMapper.update(user,queryWrapper);
System.out.println("result:" + result);
}
}
案例说明二:
//将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改
先实现前面的模糊语句再实现括号里的语句最后用and连接
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name","a")
.and(i -> i.gt("age",20).or().isNull("email"));
这里如果使用.like().gt().or().isNull()的话就和案例一一样了没有实现条件的优先级了,因此这里调用了and()方法,在and中编写lambda表达式实现条件优先
调用userMapper接口
int update = userMapper.update(user, queryWrapper);
System.out.println("update:" + update);
完整代码
package com.heima;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.mapper.UserMapper;
import com.heima.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;
import java.util.Map;
/**
* @Author 黑麻哥
* @Date 2023/12/22 13:56
* @Version 1.0
*/
@SpringBootTest
public class UserTestQueryWrapper {
@Autowired
private UserMapper userMapper;
@Test
public void testPriority(){
//将用户名中包含a并且(年龄大于20或邮箱为null)的用户信息修改
//lambda中的条件优先执行
//UPDATE user SET name=?, email=? WHERE is_deleted=0 AND (name LIKE ? AND (age > ? OR email IS NULL))
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name","a")
.and(i -> i.gt("age",20).or().isNull("email"));
User user = new User();
user.setName("小红");
user.setEmail("woaini@douyu.com");
int update = userMapper.update(user, queryWrapper);
System.out.println("update:" + update);
}
}
- 组装select子句
//查询用户的用户名,年龄,邮箱信息
只查询用户中的用户名,年龄,和邮箱
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("name","age","email");
Wrapper中select方法可以添加多个参数,实现需要的信息
调用userMapper
List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
maps.forEach(System.out::println);
完整代码
package com.heima;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.mapper.UserMapper;
import com.heima.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;
import java.util.Map;
/**
* @Author 黑麻哥
* @Date 2023/12/22 13:56
* @Version 1.0
*/
@SpringBootTest
public class UserTestQueryWrapper {
@Autowired
private UserMapper userMapper;
@Test
public void testGet2(){
//查询用户的用户名,年龄,邮箱信息
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("name","age","email");
List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
maps.forEach(System.out::println);
}
}
- 实现子查询
案例说明:
//查询id小于等于100的用户信息
可能是案例过于简单,感觉有点多余...这里就不多说了,直接给出完整代码了
package com.heima;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.mapper.UserMapper;
import com.heima.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;
import java.util.Map;
/**
* @Author 黑麻哥
* @Date 2023/12/22 13:56
* @Version 1.0
*/
@SpringBootTest
public class UserTestQueryWrapper {
@Autowired
private UserMapper userMapper;
@Test
public void testInSql(){
//查询id小于等于100的用户信息
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.inSql("uid", "select uid from t_user where uid <= 100");
List<User> list = userMapper.selectList(queryWrapper);
list.forEach(System.out::println);
}
}
5.3 UpdateWrapper
UpdateWrapper不仅拥有QueryWrapper的组装条件功能,还提供了set方法进行修改对应条件的数据库信息
案例说明:
//将用户名包含有a并且(年龄大于20或邮箱为null)的用户信息修改
使用updateWrapper的set方法修改
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.like("name","r")
.and(i -> i.gt("age",20).or().isNull("email"));
updateWrapper.set("name","foxPlayer").set("email","112233@qq.com");
调用userMapper的update方法
int result = userMapper.update(null,updateWrapper);
System.out.println("result:" + result);
完整代码
package com.heima;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.heima.mapper.UserMapper;
import com.heima.pojo.User;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author 黑麻哥
* @Date 2023/12/22 15:09
* @Version 1.0
*/
@SpringBootTest
public class UserTestUpdateWrapper {
@Resource
private UserMapper userMapper;
@Test
public void test(){
//将用户名包含有a并且(年龄大于20或邮箱为null)的用户信息修改
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.like("name","r")
.and(i -> i.gt("age",20).or().isNull("email"));
updateWrapper.set("name","foxPlayer").set("email","112233@qq.com");
int result = userMapper.update(null,updateWrapper);
System.out.println("result:" + result);
}
}
5.4 condition
在真正开发的过程中,组装条件是常见的功能,而这些条件数据来源于用户输入,是可选的,因此我们在组装这些条件时,必须先判断用户是否选择了这些条件,若选择则需要组装该条件,若没有选择则一定不能组装,以免影响SQL执行的结果
案例说明:
案例一:不使用condition语句实现查询
package com.heima;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.heima.mapper.UserMapper;
import com.heima.pojo.User;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author 黑麻哥
* @Date 2023/12/22 15:09
* @Version 1.0
*/
@SpringBootTest
public class UserTestUpdateWrapper {
@Resource
private UserMapper userMapper;
@Test
public void test2(){
//SELECT uid AS id,age,name,email,is_deleted FROM user WHERE is_deleted=0 AND (name LIKE ? AND age >= ? AND age <= ?)
String username = "";
Integer ageBegin = 20;
Integer ageEnd = 30;
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
if(StringUtils.isBlank(username)){
//isBlank判断某个字符串是否不为空字符串,不为null,不为空白符
queryWrapper.like("name",username);
}
if(ageBegin != null){
queryWrapper.ge("age",ageBegin);
}
if(ageEnd != null){
queryWrapper.le("age",ageEnd);
}
List<User> list = userMapper.selectList(queryWrapper);
list.forEach(System.out::println);
}
}
这里我们看到使用了多个if语句,代码很臃肿,这时我们可以使用condition来减少代码量
案例二:携带condition参数
package com.heima;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.heima.mapper.UserMapper;
import com.heima.pojo.User;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author 黑麻哥
* @Date 2023/12/22 15:09
* @Version 1.0
*/
@SpringBootTest
public class UserTestUpdateWrapper {
@Resource
private UserMapper userMapper;
@Test
public void test3(){
//test2的简写方式
String username = "a";
Integer ageBegin = null;
Integer ageEnd = 30;
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like(StringUtils.isNotBlank(username),"name",username)
.ge(ageBegin != null, "age", ageBegin)
.le(ageEnd != null, "age", ageEnd);
List<User> list = userMapper.selectList(queryWrapper);
list.forEach(System.out::println);
}
}
这样我们就将判断条件封装到了方法的参数上,看上去都舒服多了!
5.5 LambdaQueryWrapper
功能等同于QueryWrapper,提供了Lambda表达式的语法可以避免填错列名。
public void test(){
String username = "a";
Integer ageBegin = null;
Integer ageEnd = 30;
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> list = userMapper.selectList(queryWrapper);
list.forEach(System.out::println);
}
5.6 LambdaUpdateWrapper
功能等同于UpdateWrapper,提供了Lambda表达式的语法可以避免填错列名。
public void test1(){
//将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改
LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.like(User::getName, "a")
.and(i -> i.gt(User::getAge, 20).or().isNull(User::getEmail));
updateWrapper.set(User::getName, "小黑").set(User::getEmail,"abc@atguigu.com");
int result = userMapper.update(null, updateWrapper);
System.out.println("result:"+result);
}
6 常用插件
6.1 分页插件
MybatisPlus自带分页插件,简单配置后就可以投入使用
1.添加配置类MybatisPlusConfig
package com.heima.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusInnerInterceptorAutoConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
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;
/**
* @Author 黑麻哥
* @Date 2023/12/22 16:31
* @Version 1.0
*/
@Configuration
//扫描mapper接口所在的包
@MapperScan("com.heima.mapper")
public class MybatisPlusConfig{
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//配置分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
}
}
这里我们可以将扫描mapper包的注解@MapperScan写在这个配置类里,这里我们使用的数据源是Mysql
测试分页:
package com.heima;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.mapper.UserMapper;
import com.heima.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
/**
* @Author 黑麻哥
* @Date 2023/12/22 16:34
* @Version 1.0
*/
@SpringBootTest
public class MybatisPlusPages {
@Resource
private UserMapper userMapper;
@Test
public void testPage(){
//参数分别是当前页面,和显示的个数
Page<User> page = new Page<>(1,3);
userMapper.selectPage(page,null);
System.out.println(page.getRecords());
System.out.println(page.getPages());
}
}
6.2 自定义分页
上面调用的是MyBatis-Plus提供的带有分页的方法,我们自己也可以创建带有分页的方法,需要在userMapper中配置
- 在
UserMapper
接口中定义一个方法
/**
* 通过年龄查询用户信息并分页
* @param page Mybatis-Plus 所提供的分页对象,必须位于第一个参数的位置
* @param age
* @return
*/
Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);
- 在
UserMapper.xml
中编写SQL实现该方法
<select id="selectPageVo" resultType="User">
select id,username as name,age,email from t_user where age > #{age}
</select>
- 测试方法
package com.heima;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.mapper.UserMapper;
import com.heima.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
/**
* @Author 黑麻哥
* @Date 2023/12/22 16:34
* @Version 1.0
*/
@SpringBootTest
public class MybatisPlusPages {
@Resource
private UserMapper userMapper;
@Test
public void testPageVo(){
Page<User> page = new Page<>(1,3);
userMapper.selectPageVo(page,10);
System.out.println(page.getRecords());
System.out.println(page.getPages());
System.out.println(page.getTotal());
System.out.println(page.hasNext());
System.out.println(page.hasPrevious());
}
}
6.3 乐观锁
不一定出现线程问题,没有直接对方法上锁
作用:当要更新一条记录的时候,希望这条记录没有被别人更新
实现方式:
版本号法:
- 取出记录时,获取当前 version
- 更新时,带上这个 version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果 version 不对,就更新失败
CAS方法:
判断某一个数据字段是否改变
6.3.1 实现场景
一件商品,成本价是80元,售价是100元。老板先是通知小李,说你去把商品价格增加50元。小李正在玩游戏,耽搁了一个小时。正好一个小时后,老板觉得商品价格增加到150元,价格太高,可能会影响销量。又通知小王,你把商品价格降低30元。
此时,小李和小王同时操作商品后台系统。小李操作的时候,系统先取出商品价格100元;小王也在操作,取出的商品价格也是100元。小李将价格加了50元,并将100+50=150元存入了数据库;小王将商品减了30元,并将100-30=70元存入了数据库。是的,如果没有锁,小李的操作就完全被小王的覆盖了。
现在商品价格是70元,比成本价低10元。几分钟后,这个商品很快出售了1千多件商品,老板亏1万多。
6.3.2 乐观锁与悲观锁
上述例子,如果是乐观锁,小王保存价格前,会检查下价格是否被人修改过了。如果被修改过了,则重新取出的是被修改后的价格,150元,这样他会将120元存入数据库。
如果是悲观锁,小李取出数据后,系统只能由小李操作,小王只能等小李操作完之后,才能对价格进行操作,也会保证最终的价格是120元。
6.3.3 模拟修改冲突
数据库中增加商品表
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);
添加一个实体类Product
@Data
public class Product {
private Long id;
private String name;
private Integer price;
private Integer version;
}
添加一个Mapper接口ProductMapper
package com.heima.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.heima.pojo.Product;
import org.springframework.stereotype.Repository;
/**
* @Author 黑麻哥
* @Date 2023/12/23 9:26
* @Version 1.0
*/
@Repository
public interface ProductMapper extends BaseMapper<Product> {
}
测试方法
package com.heima;
import com.heima.mapper.ProductMapper;
import com.heima.pojo.Product;
import com.heima.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @Author 黑麻哥
* @Date 2023/12/23 9:22
* @Version 1.0
*/
@SpringBootTest
public class MybatisPlusLock {
@Autowired
private ProductMapper productMapper;
@Test
public void optLock1(){
//小李和小王同时获取到价格,同时修改价格,不加乐观锁,测试时不加乐观锁插件
//小李获取商品的价格
Product productLi = productMapper.selectById(1);
System.out.println("小李获取的价格为:" + productLi.getPrice());
//小王获取商品的价格
Product productWang = productMapper.selectById(1);
System.out.println("小王获取的价格为:" + productWang.getPrice());
//小李将价格增加50
productLi.setPrice(productLi.getPrice() + 50);
productMapper.updateById(productLi);
//然后小王再将价格降低30
productWang.setPrice(productWang.getPrice() - 30);
productMapper.updateById(productWang);
//老板获取商品的价格
Product productBoss = productMapper.selectById(1);
System.out.println("老板获取的价格为:" + productBoss.getPrice());
}
}
执行结果
6.3.4 乐观锁解决问题
实体类version字段添加注解@Version
@Data
public class Product {
private Long id;
private String name;
private Integer price;
@Version
private Integer version;
}
添加乐观锁插件配置
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//添加分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//添加乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
测试方法:
@Test
public void optLock2(){
//小李和小王同时获取到价格,同时修改价格,增加乐观锁(版本号法)
//小李获取商品的价格
Product productLi = productMapper.selectById(1);
System.out.println("小李获取的价格为:" + productLi.getPrice());
//小王获取商品的价格
Product productWang = productMapper.selectById(1);
System.out.println("小王获取的价格为:" + productWang.getPrice());
//小李将价格增加50
//UPDATE product SET name=?, price=?, version=? WHERE id=? AND version=?
productLi.setPrice(productLi.getPrice() + 50);
productMapper.updateById(productLi);
//然后小王再将价格降低30
productWang.setPrice(productWang.getPrice() - 30);
productMapper.updateById(productWang);
//老板获取商品的价格
Product productBoss = productMapper.selectById(1);
System.out.println("老板获取的价格为:" + productBoss.getPrice());
}
优化执行流程,小李执行完成后,判断小王执行的结果,如果执行失败,则重新从数据库中获取价格和版本号信息
@Test
public void optLock3(){
//小李和小王同时获取到价格,同时修改价格,增加乐观锁(版本号法)
//小李获取商品的价格
Product productLi = productMapper.selectById(1);
System.out.println("小李获取的价格为:" + productLi.getPrice());
//小王获取商品的价格
Product productWang = productMapper.selectById(1);
System.out.println("小王获取的价格为:" + productWang.getPrice());
//小李将价格增加50
productLi.setPrice(productLi.getPrice() + 50);
productMapper.updateById(productLi);
//再让小王将价格降低30
productWang.setPrice(productWang.getPrice() - 30);
int result = productMapper.updateById(productWang);
if(result == 0){
//操作失败,重试
Product productNew = productMapper.selectById(1);
productNew.setPrice(productNew.getPrice()-30);
productMapper.updateById(productNew);
}
//老板获取商品的价格
Product productBoss = productMapper.selectById(1);
System.out.println("老板获取的价格为:" + productBoss.getPrice());
}
执行结果
7 通用枚举
表中的有些字段值是固定的,例如性别(男或女),此时我们可以使用MyBatis-Plus的通用枚举来实现
数据库表添加字段sex
创建通用枚举类型
package com.heima.enums;
import com.baomidou.mybatisplus.annotation.EnumValue;
import lombok.Getter;
/**
* @Author 黑麻哥
* @Date 2023/12/23 10:15
* @Version 1.0
*/
@Getter
public enum SexEnum {
MALE(0,"男"),
FEMALE(1,"女");
@EnumValue //将注解锁标识的属性的值存储到数据库中
private Integer sex;
private String sexName;
SexEnum(Integer sex, String sexName) {
this.sex = sex;
this.sexName = sexName;
}
}
User实体类中添加属性sex
public class User {
private Long id;
@TableField("username")
private String name;
private Integer age;
private String email;
@TableLogic
private int isDeleted; //逻辑删除
private SexEnum sex;
}
yml配置扫描通用枚举
#MyBatis-Plus相关配置
mybatis-plus:
#指定mapper文件所在的地址
mapper-locations: classpath:mapper/*.xml
configuration:
#配置日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
banner: off
db-config:
#配置mp的主键策略为自增
id-type: auto
# 设置实体类所对应的表的统一前缀
table-prefix: t_
#配置类型别名所对应的包
type-aliases-package: com.atguigu.mybatisplus.pojo
# 扫描通用枚举的包
type-enums-package: com.atguigu.mybatisplus.enums
执行测试方法
package com.heima;
import com.heima.enums.SexEnum;
import com.heima.mapper.UserMapper;
import com.heima.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @Author 黑麻哥
* @Date 2023/12/23 10:17
* @Version 1.0
*/
@SpringBootTest
public class MybatisPlusEnums {
@Autowired
private UserMapper userMapper;
@Test
public void test(){
User user = new User();
user.setName("meiko");
user.setAge(23);
user.setSex(SexEnum.MALE);
int result = userMapper.insert(user);
System.out.println("Result:" + result);
}
}
8 多数据源
适用于多种场景:纯粹多库、 读写分离、 一主多从、 混合模式等
场景说明:
我们创建两个库,分别为:mybatis_plus(以前的库不动)与mybatis_plus_1(新建),将mybatis_plus库的product表移动到mybatis_plus_1库,这样每个库一张表,通过一个测试用例分别获取用户数据与商品数据,如果获取到说明多库模拟成功
8.1 创建数据库及表
创建数据库mybatis_plus_1和表`product
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;
8.2 新建工程引入依赖
自行新建一个Spring Boot工程并选择MySQL驱动及Lombok依赖
引入MyBaits-Plus的依赖及多数据源的依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency><dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
8.3 编写配置文件
yml配置文件
spring:
# 配置数据源信息
datasource:
dynamic:
# 设置默认的数据源或者数据源组,默认值即为master
primary: master
# 严格匹配数据源,默认false.true未匹配到指定数据源时抛异常,false使用默认数据源
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 132537
slave_1:
url: jdbc:mysql://localhost:3306/mybatis_plus_1?characterEncoding=utf-8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 132537
8.4 创建实体类
新建一个User实体类(如果数据库表名有t_前缀记得配置)
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
新建一个实体类Product
@Data
public class Product {
private Long id;
private String name;
private Integer price;
private Integer version;
}
8.5 创建Mapper及Service
新建接口UserMapper
public interface UserMapper extends BaseMapper<User> {}
新建接口ProductMapper
public interface ProductMapper extends BaseMapper<Product> {}
新建Service接口UserService指定操作的数据源
@DS("master") //指定操作的数据源,master为user表
public interface UserService extends IService<User> {}
新建Service接口ProductService指定操作的数据源
@DS("slave_1")
public interface ProductService extends IService<Product> {}
自行建立Service的实现类
...
8.6 编写测试方法
记得在启动类中添加注解@MapperScan()
class TestDatasourceApplicationTests {
@Resource
UserService userService;
@Resource
ProductService productService;
@Test
void contextLoads() {
User user = userService.getById(1L);
Product product = productService.getById(1L);
System.out.println("User = " + user);
System.out.println("Product = " + product);
}
}