文章目录
一、简介
MyBatis-Plus 官方文档
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window) 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
自动生成单表的CRUD功能
提供丰富的条件拼接方式
全自动ORM类型持久层框架
二、快速入门
- 准备数据库
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Doug', 18, 'test1@baomidou.com'),
(2, 'Wake', 20, 'test2@baomidou.com'),
(3, 'Tim', 28, 'test3@baomidou.com'),
(4, 'Morty', 21, 'test4@baomidou.com'),
(5, 'Theo', 30, 'test5@baomidou.com'),
(6, 'BilBli', 24, 'test6@baomidou.com');
-
创建空工程 mybatis-plus-part
-
创建模块 mybatis-plus-quick-01
-
导入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.5</version>
</parent>
<groupId>com.wake</groupId>
<artifactId>mybatis-plus-quick-01</artifactId>
<version>1.0-SNAPSHOT</version>
<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>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
<!-- 数据库相关配置启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- druid启动器的依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-3-starter</artifactId>
<version>1.2.18</version>
</dependency>
<!-- 驱动类-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version>
</dependency>
</dependencies>
<!-- SpringBoot应用打包插件-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- 配置文件和启动类
- 文件:META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
- 内容:
com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceAutoConfigure
- application.yaml
# 连接池配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
url: jdbc:mysql:///mybatis-example
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
- 启动类
@MapperScan("com.wake.mapper")
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class,args);
}
}
- 功能编码
- pojo
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
- mapper 接口
public interface UserMapper extends BaseMapper<User> {
}
- 测试与使用
@SpringBootTest
public class SpringBootMybatisPlusTest {
@Autowired
private UserMapper userMapper;
@Test
public void test() {
List<User> userList = userMapper.selectList(null);
System.out.println(userList);
}
}
使用
BaseMapper<User>
已经定义好的方法,实现单表简单的增删改查。
集成MyBatis-Plus
非常的简单,只需要引入 starter 工程,并配置 mapper 扫描路径即可。
三、MyBatis-Plus核心功能
- mybatis :
-
- mapper 接口 crud方法
-
- mapper.xml crud sql语句
-
- mybatis-plus :
-
- mapper接口 extends BaseMapper
-
- crud方法 crud的sql
-
3.1 基于Mapper接口CRUD
通用 CRUD 封装BaseMapper (opens new window)接口,
Mybatis-Plus
启动时自动解析实体表关系映射转换为Mybatis
内部对象注入容器! 内部包含常见的单表操作!
3.1.1 Insert方法
// 插入一条记录
// T 就是要插入的实体对象
// 默认主键生成策略为雪花算法
int insert(T entity);
类型 | 参数名 | 描述 |
---|---|---|
T | entity | 实体对象 |
- 实例:
@Test
public void insert_test(){
User user = new User();
user.setName("Sam");
user.setAge(39);
user.setEmail("1900@qq.com");
int rows = userMapper.insert(user);
System.out.println(" insert rows : "+rows);
}
3.1.2 Delete方法
// 根据 entity 条件,删除记录
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
// 删除(根据ID 批量删除)
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 ID 删除
int deleteById(Serializable id);
// 根据 columnMap 条件,删除记录
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
类型 | 参数名 | 描述 |
---|---|---|
Wrapper<T> | wrapper | 实体对象封装操作类(可以为 null) |
Collection<? extends Serializable> | idList | 主键 ID 列表(不能为 null 以及 empty) |
Serializable | id | 主键 ID |
Map<String, Object> | columnMap | 表字段 map 对象 |
- 实例:
@Test
public void delete_test(){
int rowId = userMapper.deleteById(1767589005571969025L);
System.out.println(" deleteById rows : "+rowId);
Map map = new HashMap();
map.put("age",28); // age = 28
int rowMap = userMapper.deleteByMap(map);
System.out.println(" deleteByMap rows : "+rowMap);
}
3.1.3 Update方法
// 根据 whereWrapper 条件,更新记录
int update(@Param(Constants.ENTITY) T updateEntity,
@Param(Constants.WRAPPER) Wrapper<T> whereWrapper);
// 根据 ID 修改 主键属性必须值
int updateById(@Param(Constants.ENTITY) T entity);
类型 | 参数名 | 描述 |
---|---|---|
T | entity | 实体对象 (set 条件值,可为 null) |
Wrapper<T> | updateWrapper | 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句) |
- 实例:
@Test
public void update_test(){
//update 当属性值为Null时,不修改!
User user = new User();
user.setId(1L);
user.setAge(25);
// 按照Id,只修改age
int i = userMapper.updateById(user);
System.out.println("update i ID : " + i);
//将所有人年龄改为18
User user1 = new User();
user1.setAge(18);
int rows = userMapper.update(user1, null);
System.out.println("update rows ALL : " + rows);
}
3.1.4 Select方法
// 根据 ID 查询
T selectById(Serializable id);
// 根据 entity 条件,查询一条记录
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 查询(根据ID 批量查询)
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 entity 条件,查询全部记录
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 查询(根据 columnMap 条件)
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
// 根据 Wrapper 条件,查询全部记录
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 entity 条件,查询全部记录(并翻页)
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录(并翻页)
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询总记录数
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
- 参数说明:
类型 | 参数名 | 描述 |
---|---|---|
Serializable | id | 主键 ID |
Wrapper<T> | queryWrapper | 实体对象封装操作类(可以为 null) |
Collection<? extends Serializable> | idList | 主键 ID 列表(不能为 null 以及 empty) |
Map<String, Object> | columnMap | 表字段 map 对象 |
IPage<T> | page | 分页查询条件(可以为 RowBounds.DEFAULT) |
- 实例:
@Test
public void select_test(){
User user = userMapper.selectById(1);
System.out.println("user : "+user);
// ids集合查询
List<Long> ids = new ArrayList<>();
ids.add(1L);
ids.add(2L);
List<User> users = userMapper.selectBatchIds(ids);
System.out.println("users = " + users);
}
3.1.5 自定义和多表映射
- mybatis-plus的默认mapperxml位置
mybatis-plus: # mybatis-plus的配置
# 默认位置 private String[] mapperLocations = new String[]{"classpath*:/mapper/**/*.xml"};
mapper-locations: classpath:/mapper/*.xml
- 自定义mapper方法:
public interface UserMapper extends BaseMapper<User> {
//正常自定义方法!
//可以使用注解@Select或者mapper.xml实现
List<User> queryAll();
}
- 基于mapper.xml实现:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace = 接口的全限定符 -->
<mapper namespace="com.wake.mapper.UserMapper">
<select id="queryAll" resultType="user" >
select * from user
</select>
</mapper>
3.2 基于Service接口CRUD
通用 Service CRUD 封装IService (opens new window)接口,进一步封装 CRUD 采用
get 查询单行
remove 删除
list 查询集合
page 分页
前缀命名方式区分Mapper
层避免混淆,
3.2.1 对比Mapper接口CRUD区别:
- service添加了批量方法
- service层的方法自动添加事务
3.2.2 使用Iservice接口方式
- service 接口
- 继承的接口是一半实现一半没实现
public interface UserService extends IService<User> {
}
- service 实现类
- 实现service接口,在继承实现的方法
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
3.2.3 CRUD方法介绍
保存:
// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);
修改或者保存:
// TableId 注解存在更新记录,否插入一条记录;(没写要修改的ID 就变成插入一条信息)
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
移除:
// 根据 queryWrapper 设置的条件,删除记录
boolean remove(Wrapper<T> queryWrapper);
// 根据 ID 删除
boolean removeById(Serializable id);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map<String, Object> columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection<? extends Serializable> idList);
更新:
// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根据 whereWrapper 条件,更新记录
boolean update(T updateEntity, Wrapper<T> whereWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);
数量:
// 查询总记录数
int count();
// 根据 Wrapper 条件,查询总记录数
int count(Wrapper<T> queryWrapper);
查询:
// 根据 ID 查询
T getById(Serializable id);
// 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
// 根据 Wrapper,查询一条记录
Map<String, Object> getMap(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
集合:
// 查询所有
List<T> list();
// 查询列表
List<T> list(Wrapper<T> queryWrapper);
// 查询(根据ID 批量查询)
Collection<T> listByIds(Collection<? extends Serializable> idList);
// 查询(根据 columnMap 条件)
Collection<T> listByMap(Map<String, Object> columnMap);
// 查询所有列表
List<Map<String, Object>> listMaps();
// 查询列表
List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper);
// 查询全部记录
List<Object> listObjs();
// 查询全部记录
<V> List<V> listObjs(Function<? super Object, V> mapper);
// 根据 Wrapper 条件,查询全部记录
List<Object> listObjs(Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录
<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
3.3 分页查询实现
- 导入分页插件
在启动类中添加:
/**
* 将 mybatis-plus 插件加入到IOC容器
* @return
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
//mybatis-plus的插件集合【将需要的插件加入到这个集合中即可,比如分页插件,乐观锁插件等】
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
//分页插件
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return mybatisPlusInterceptor;
}
- 使用分页查询
@Test
public void testPage(){
//IPage -> Page(当前页,当前页容量)
Page<User> userPage = new Page<>(1, 3);
userMapper.selectPage(userPage,null);
//结果page最后也会封装结果
long current = userPage.getCurrent();//页码
long size = userPage.getSize();//页容量
List<User> records = userPage.getRecords();//当前页数据
long total = userPage.getTotal();//总条数
}
- 自定义的mapper方法使用分页
- 接口定义
public interface UserMapper extends BaseMapper<User> {
/**
* 定义一个根据年龄参数查询,并且分页的方法 age > xx
* @param page
* @param age
* @return
*/
IPage<User> queryByAge(IPage<User> page,@Param("age") Integer age);
}
- 接口实现
<mapper namespace="com.wake.mapper.UserMapper">
<!-- 集合泛型的情况 resultType 就写Page的泛型内的类型 -->
<select id="queryByAge" resultType="com.wake.pojo.User">
select * from user where age > #{age}
</select>
</mapper>
- 测试
soutv 快捷键
@Test
public void testMyPage(){
//IPage -> Page(当前页,当前页容量)
Page<User> userPage = new Page<>(1, 3);
userMapper.queryByAge(userPage,17);
//结果page最后也会封装结果
long current = userPage.getCurrent();//页码
System.out.println("current = " + current);
long size = userPage.getSize();//页容量
System.out.println("size = " + size);
List<User> records = userPage.getRecords();//当前页数据
System.out.println("records = " + records);
long total = userPage.getTotal();//总条数
System.out.println("total = " + total);
}
3.4 条件构造器使用 Wrapper
3.4.1 条件构造器作用
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "John"); // 添加等于条件
queryWrapper.ne("age", 30); // 添加不等于条件
queryWrapper.like("email", "@gmail.com"); // 添加模糊匹配条件
等同于:
delete from user where name = "John" and age != 30
and email like "%@gmail.com%"
// 根据 entity 条件,删除记录
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
使用MyBatis-Plus的条件构造器,你可以构建灵活、高效的查询条件,而不需要手动编写复杂的 SQL 语句。
它提供了许多方法来支持各种条件操作符,并且可以通过链式调用来组合多个条件。
这样可以简化查询的编写过程,并提高开发效率。
3.4.2 条件构造器继承结构
Wrapper : 条件构造抽象类,最顶端父类
- AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件
- QueryWrapper : 查询/删除条件封装
- UpdateWrapper : 修改条件封装
- AbstractLambdaWrapper : 使用Lambda 语法
- LambdaQueryWrapper :用于Lambda语法使用的查询Wrapper
- LambdaUpdateWrapper : Lambda 更新封装Wrapper
3.4.3 基于 QueryWrapper 组装条件
- 组装查询条件:
/**
* 查询用户名包含 o like , 年龄在20-30之间,并且邮箱不为空的用户信息
*/
@Test
public void test_01(){
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.between("age",20,30)
.like("name","o")
.isNotNull("email");
List<User> userList = userMapper.selectList(userQueryWrapper);
System.out.println("userList = " + userList);
}
- 组装排序条件:
/**
* 按年龄降序查询用户,如果年龄相同则按id升序排列
*/
@Test
public void test_02(){
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.orderByDesc("age").orderByAsc("id");
List<User> userList = userMapper.selectList(userQueryWrapper);
System.out.println("userList = " + userList);
}
- 组装删除条件:
- 查询为空的条件,使用delect语句
/**
* 删除email为空的用户
*/
@Test
public void test_03(){
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.isNull("email");
int delete = userMapper.delete(userQueryWrapper);
System.out.println("delete = " + delete);
}
- and和or关键字使用(修改):
/**
* 将年龄大于20并且用户名中包含有a或邮箱为null的用户信息修改
*/
@Test
public void test_04(){
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.gt("age",20)
.like("name","a")
.or()
.isNull("email");
User user = new User();
user.setName("维克");
int update = userMapper.update(user, userQueryWrapper);
System.out.println("update = " + update);
}
不加
or
默认都是用and
连接
- 指定列映射查询:
/**
* 查询用户信息的name和age字段
*/
@Test
public void test_05(){
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.select("name","age");
List<User> userList = userMapper.selectList(userQueryWrapper);
System.out.println("userList = " + userList);
}
- condition判断组织条件:
- 前端传入两个参数 age , name
/**
* 动态语句-》判断条件拼接
* 前端传入两个参数 name 与 age
* name不为空 ,作为条件 = 查询
* age > 18 , 作为条件,查询等于=age
*/
@Test
public void test_06() {
//模拟前端假数据
Integer age = 25;
String name = "Doug";
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
方法一:自写if前置条件
//if (StringUtils.isNotBlank(name)) {
// userQueryWrapper.eq("name", name);
//}
因为是假数据 写了固定值所以爆黄 一定为TRUE
//if (age != null && age > 18) {
// userQueryWrapper.eq("age",age);
//}
// 方法二:使用mybatis-plus方法
//每个方法都有会有一个boolean condition,
//可以放置一个比较表达式,为TRUE整个条件生效执行,为FALSE不生效不执行
//eq(boolean condition, R column, Object val)
userQueryWrapper.eq(StringUtils.isNotBlank(name),"name",name);
userQueryWrapper.eq(age != null && age > 18,"age",age);
userMapper.selectList(userQueryWrapper);
}
非常复杂的sql还是自己写
3.4.4 基于 UpdateWrapper组装条件
- 使用queryWrapper:
-
- 需要准备 要修改的实体类数据
-
- 不能改为Null
-
/**
* 将年龄大于20并且用户名中包含有a或邮箱为null的用户信息修改
*/
@Test
public void test_04() {
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.gt("age", 20)
.like("name", "a")
.or()
.isNull("email");
User user = new User();
user.setName("维克");
int update = userMapper.update(user, userQueryWrapper);
System.out.println("update = " + update);
}
- 使用updateWrapper:
-
- 直接携带修改数据 set(“列名”,“值”)
-
- 指定任意修改得值 set(“列名”,null)
-
@Test
public void test_04() {
UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
userUpdateWrapper.gt("age", 20)
.like("name", "a")
.or()
.isNull("email")
.set("email",null)
.set("age",99);
int update = userMapper.update(null, userUpdateWrapper);
System.out.println("update = " + update);
3.4.5 基于 LambdaQueryWrapper组装条件
- LambdaQueryWrapper对比QueryWrapper优势
QueryWrapper 示例代码:
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.between("age", 20, 30)
.like("name", "o")
.isNotNull("email");
LambdaQueryWrapper 示例代码:
LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
userLambdaQueryWrapper.between(User::getAge,20,30)
.like(User::getName,"o")
.isNotNull(User::getEmail);
LambdaQueryWrapper 使用了实体类的属性引用(例如
User::getName
、User::getAge
),而不是字符串来表示字段名
- lambda表达式回顾
-
参数列表: 参数列表用小括号
()
括起来,可以指定零个或多个参数。如果没有参数,可以省略小括号;如果只有一个参数,可以省略小括号。示例:
(a, b)
,x ->
,() ->
-
箭头符号: 箭头符号
->
分割参数列表和 Lambda 表达式的主体部分。示例:
->
-
Lambda 表达式的主体: Lambda 表达式的主体部分可以是一个表达式或一个代码块。如果是一个表达式,可以省略 return 关键字;如果是多条语句的代码块,需要使用大括号
{}
括起来,并且需要明确指定 return 关键字。示例:
- 单个表达式:
x -> x * x
- 代码块:
(x, y) -> { int sum = x + y; return sum; }
- 单个表达式:
System.out::println;
() -> 类.XXX(); -> 类::方法名
- 方法引用回顾:
- 静态方法引用: 引用静态方法,语法为
类名::静态方法名
。 - 实例方法引用: 引用实例方法,语法为
实例对象::实例方法名
。 - 对象方法引用: 引用特定对象的实例方法,语法为
类名::实例方法名
。 - 构造函数引用: 引用构造函数,语法为
类名::new
。
List<String> names = Arrays.asList("John", "Tom", "Alice");
// 使用 Lambda 表达式
names.forEach(name -> System.out.println(name));
// 使用方法引用
names.forEach(System.out::println);
- lambdaQueryWrapper使用案例:
技巧: 类名::方法名
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//注意: 需要使用方法引用
//技巧: 类名::方法名
lambdaQueryWrapper.eq(!StringUtils.isEmpty(name), User::getName,name);
3.4.6 基于 LambdaUpdateWrapper组装条件
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
//将id = 3 的email设置为null, age = 18
updateWrapper.eq("id",3)
.set("email",null) // set 指定列和结果
.set("age",18);
//使用lambdaUpdateWrapper
LambdaUpdateWrapper<User> updateWrapper1 = new LambdaUpdateWrapper<>();
updateWrapper1.eq(User::getId,3)
.set(User::getEmail,null)
.set(User::getAge,18);
3.5 核心注解使用
3.5.1 理解和介绍
MyBatis-Plus提供了一种基于注解的方式来定义和映射数据库操作。
public interface UserMapper extends BaseMapper<User> {
}
- 此接口对应的方法为什么会自动触发 user表的crud呢?
- 默认情况下, 根据指定的<实体类>的名称对应数据库表名,属性名对应数据库的列名!
- 但是不是所有数据库的信息和实体类都完全映射!
- 例如:表名 t_user → 实体类 User
这时候就可以使用mybatis-plus提供的注解实现自定义映射关系
3.5.2 @TableName注解
实体类上标注,对应数据库的表名,忽略大小写!
当数据库的表名和实体类命名不同(忽略大小写),使用@TableName注解 标注指定数据库表名。
BaseMapper -> User实体类 -> 实体类的名字 -> 表名数据库操作
特殊情况:如果表名和实体类名相同(忽略大小写)可以省略该注解!
其他解决方案:全局设置前缀 (基本配置_mybatis-plus配置类yml)
global-config:
db-config:
table-prefix: t_ #定义全局表名前缀 就不用在每个实体类上添加注解
3.5.3 @TableId 注解
主键注解,实体类主键字段Id中使用
@TableName("t_user")
public class User {
@TableId(value="主键列名",type=主键策略)
private Long id;
private String name;
private Integer age;
private String email;
}
属性 | 类型 | 必须指定 | 默认值 | 描述 |
---|---|---|---|---|
value | String | 否 | “” | 主键字段名 |
type | Enum | 否 | IdType.NONE | 指定主键类型 |
默认IdType 是: 雪花算法
-
- 数据库主键 为 bigInt / varchar(64)
-
- 实体类Long类型
-
- 随机生成一个数据,给主键值(不重复)
可以设置主键自增 IdType : auto
-
- mysql数据库 表主键定义时 类型 数字 auto_increment
-
- 插入数据会自增长
雪花算法:随机生成一个Long类型的不重复数字
UUID : 随机生成一个不重复的字符串
值 | 描述 |
---|---|
AUTO | 数据库 ID 自增 (mysql配置主键自增长) |
ASSIGN_ID(默认) | 分配 ID(主键类型为 Number(Long )或 String)(since 3.3.0),使用接口IdentifierGenerator 的方法nextId (默认实现类为DefaultIdentifierGenerator 雪花算法) |
- 插入一条数据 测试
@Test
public void insert_test(){
User user = new User();
user.setName("rick");
user.setAge(66);
user.setEmail("Snowflake_ID@wake.com");
// 主键不要赋值
// 主键策略:雪花算法 -> 不重复数字Long
int rows = userMapper.insert(user);
System.out.println(" insert rows : "+rows);
}
3.5.4 雪花算法使用场景
为什么使用UUID 或 雪花算法:
-
当一张表的数据量过大时:可以进行分表操作,竖切和横切 分表。
-
竖切 分为冷表/热表 这时不涉及主键ID的问题,冷热两表 实际还是同一张表。
-
横切 假设分三张表,第一张表主键1-9 第二张表主键10-20 第三张表21-30 , 三张表实际都来自同一个实体
- 当我向第一张表添加数据时,如果是使用自增auto,就会出现主键重复问题
-
-
而 UUID 算法比较麻烦,还是字符串,数值较长,效率低。
-
所以使用雪花算法!
- 雪花算法生成的数字,需要使用Long 或者 String类型主键
- 雪花算法生成的数字,需要使用Long 或者 String类型主键
3.5.5 @TableField
字段注解
@Data
public class User {
private Long id;
@TableField(value = "nickname",exist = false)
private String name;
private Integer age;
private String email;
}
MyBatis-Plus会自动开启驼峰命名风格映射
总结
mybatis pageHelper 分页 原理
就是后置拦截器