• 一篇玩转mybatis-plus框架的详细讲解(入门必备)


     🐼个人主页:爪哇斗罗

    🐼博主介绍:一名打工人

    🐼签名:圣人之道,为而不争。

    🐼一起交流,一起进步,一起互动。

    在这里插入图片描述

    目录

    1. MybatisPlus简介与特性

    1.1 简介

    1.2 特性

    2. MybatisPlus的开发环境搭建

    2.1 创建User表

    2.2 创建SpringBoot工程

    2.3 配置application.yml

    2.4 创建UserMapper并扫描

    2.5 测试环境

    3. 测试BaseMapper的增删改查

    3.1 增加用户

    3.2 删除用户

    3.3 修改用户信息

    3.4 查询用户

    4. 通用Service接口测试

    5. MybatisPlus的常用注解

    5.1 @TableName

    5.2 @TabeId

    5.3 @TabeFiled

    5.4 @TableLogic

    7. 条件构造器介绍

    7.1 QueyWrapper查询条件组装

    7.2 QueyWrapper组装排序条件

    7.3 QueryWrapper组装删除条件

    7.4 QueyWrapper组装修改条件

    7.5 UpdateWrapper组装修改条件

    8. LambdaQueryWrapper与LambdaUpdateWrapper

    9. LambdaQueryWrapper分页功能

    9.1 配置分页插件


     

    1. MybatisPlus简介与特性

    1.1 简介

    MybatisPlus作为MyBatis的一款增强工具,就是为了简化开发,为提高效率而生。同时还提供通用的Mapper与Service,无需写SQL的情况下对表进行增删改查,可以说是十分之优秀。

    1.2 特性

    在其官网上,我们可以了解到这款优秀框架的特性:

    2. MybatisPlus的开发环境搭建

    2.1 创建User表

    user表SQL如下:

    1. CREATE TABLE user (
    2. id BIGINT ( 20 ) NOT NULL COMMENT '主键ID',
    3. name VARCHAR ( 10 ) DEFAULT NULL COMMENT '姓名',
    4. age INT ( 11 ) DEFAULT NULL COMMENT '年龄',
    5. email VARCHAR ( 50 ) DEFAULT NULL COMMENT '邮箱',
    6. PRIMARY KEY ( id )
    7. ) ENGINE = INNODB DEFAULT CHARSET = utf8;

    2.2 创建SpringBoot工程

    请使用IDEA快速创建一个SpringBoot的工程,在pom.xml中导入以下依赖,实体类User.java请自行创建。

    1. <dependency>
    2. <groupId>com.baomidougroupId>
    3. <artifactId>mybatis-plus-boot-starterartifactId>
    4. <version>3.2.0version>
    5. dependency>
    6. <dependency>
    7. <groupId>org.projectlombokgroupId>
    8. <artifactId>lombokartifactId>
    9. <version>1.18.20version>
    10. dependency>
    11. <dependency>
    12. <groupId>mysqlgroupId>
    13. <artifactId>mysql-connector-javaartifactId>
    14. <scope>runtimescope>
    15. dependency>

    2.3 配置application.yml

    application.yml配置数据库连接以及mybatis日志打印:

    1. spring:
    2. application:
    3. name: mybatisplus
    4. datasource:
    5. # 数据源
    6. type: com.zaxxer.hikari.HikariDataSource
    7. # 驱动类
    8. driver-class-name: com.mysql.cj.jdbc.Driver
    9. # 数据库连接
    10. url: jdbc:mysql://localhost:3306/my?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    11. # 用户名
    12. username: root
    13. #密码
    14. password: root
    15. mybatis-plus:
    16. configuration:
    17. # 控制台日志打印
    18. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

    2.4 创建UserMapper并扫描

    1. package com.jektong.mybatisplus.mapper;
    2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    3. import com.jektong.mybatisplus.pojo.User;
    4. import org.springframework.stereotype.Repository;
    5. /**
    6. * @author jektong
    7. * @date 2022年11月04日 1:14
    8. */
    9. @Repository
    10. public interface UserMapper extends BaseMapper {
    11. }

    主启动类进行Mapper的扫描将接口注入至容器中: 

    2.5 测试环境

    1. package com.jektong.mybatisplus;
    2. import com.jektong.mybatisplus.mapper.UserMapper;
    3. import com.jektong.mybatisplus.pojo.User;
    4. import org.junit.Test;
    5. import org.junit.runner.RunWith;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.boot.test.context.SpringBootTest;
    8. import org.springframework.test.context.junit4.SpringRunner;
    9. import java.util.List;
    10. @RunWith(SpringRunner.class)
    11. @SpringBootTest
    12. public class MybatisplusApplicationTests {
    13. @Autowired
    14. private UserMapper userMapper;
    15. @Test
    16. public void contextLoads() {
    17. // 调用mybatisplus提供的共通查询方法
    18. List users = userMapper.selectList(null);
    19. // 输出
    20. users.forEach(System.out::println);
    21. }
    22. }

    测试结果:打印出SQL语句并输出数据。

    3. 测试BaseMapper的增删改查

    3.1 增加用户

    添加用户时使用insert方法,ID自动生成使用的是雪花算法

    1. @Test
    2. public void test02() {
    3. // 创建用户对象
    4. User user = new User();
    5. user.setName("钱三");
    6. user.setAge(20);
    7. user.setEmail("qiansan@qq.com");
    8. userMapper.insert(user);
    9. System.out.println("添加的用户ID="+user.getId());
    10. }

    执行程序如下:

    3.2 删除用户

    根据ID进行单个删除

    1. @Test
    2. public void testDeleteById() {
    3. // 指定删除的ID
    4. userMapper.deleteById(1588548601091469313L);
    5. System.out.println("用户ID=1588548601091469313已被删除");
    6. }

    执行程序如下:

    根据ID进行批量删除

    1. @Test
    2. public void testDeleteByBatchId() {
    3. // 指定删除的ID
    4. List ids = new ArrayList<>();
    5. ids.add(1);
    6. ids.add(2);
    7. userMapper.deleteBatchIds(ids);
    8. System.out.println("用户ID=1,2已被删除");
    9. }

    构造Map条件进行删除

    1. @Test
    2. public void testDeleteById() {
    3. // 构建删除条件
    4. Map map = new HashMap();
    5. map.put("name","小张");
    6. map.put("age","22");
    7. userMapper.deleteByMap(map);
    8. }

    执行程序如下: 

    3.3 修改用户信息

    通过updateById进行删除:

    1. @Test
    2. public void testUpdateByBatchId() {
    3. // 指定修改的ID
    4. User user = new User();
    5. user.setId(4L);
    6. user.setAge(20);
    7. user.setName("za");
    8. userMapper.updateById(user);
    9. System.out.println("用户ID=4已被修改");
    10. }

    程序执行如下:

    3.4 查询用户

    查询用户,有以下这些查询的方法通过ID,批量传入ID,以及构建map条件进行查询数据。

    不过对于复杂的条件查询,会根据条件构造器进行复杂的查询之后再说。 

    1. @Test
    2. public void testSelectUser() {
    3. userMapper.selectById(4l);
    4. // 查询全部
    5. List<User> users = userMapper.selectList(null);
    6. // map构建查询
    7. Map<String,Object> map = new HashMap();
    8. map.put("age","20");
    9. List<User> users1 = userMapper.selectByMap(map);
    10. // id批量查询
    11. Set<Long> ids = new HashSet<>();
    12. ids.add(4L);
    13. ids.add(3L);
    14. List<User> users2 = userMapper.selectBatchIds(ids);
    15. //分别输出
    16. users.forEach(System.out::println);
    17. users1.forEach(System.out::println);
    18. users2.forEach(System.out::println);
    19. }

    查询执行如下:

    4. 通用Service接口测试

    同样对于service层,也提供了通用service的增删改查的用法。首先建立UserService接口。此接口需要继承通用Service(IService)。

    UserService.java

    1. package com.jektong.mybatisplus.service;
    2. import com.baomidou.mybatisplus.extension.service.IService;
    3. import com.jektong.mybatisplus.pojo.User;
    4. /**
    5. * @author jektong
    6. * @date 2022年11月06日 20:25
    7. */
    8. public interface UserService extends IService {
    9. }

    建立它的实现类UserServiceImpl.java

    1. package com.jektong.mybatisplus.service.impl;
    2. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    3. import com.jektong.mybatisplus.mapper.UserMapper;
    4. import com.jektong.mybatisplus.pojo.User;
    5. import com.jektong.mybatisplus.service.UserService;
    6. /**
    7. * @author jektong
    8. * @date 2022年11月06日 20:36
    9. */
    10. @Service
    11. public class UserServiceImpl extends ServiceImpl implements UserService {
    12. }

    下面就来简单测试service中提供的方法,查询总记录数与批量插入

    1. @Test
    2. public void testUser() {
    3. // 查询总记录数
    4. int count = userService.count();
    5. System.out.println(count);
    6. // 批量插入
    7. List userList = new ArrayList<>();
    8. User user1 = new User();
    9. user1.setName("ab");
    10. user1.setAge(23);
    11. user1.setEmail("ab@qq.com");
    12. userList.add(user1);
    13. User user2 = new User();
    14. user2.setName("abc");
    15. user2.setAge(23);
    16. user2.setEmail("abc@qq.com");
    17. userList.add(user2);
    18. userService.saveBatch(userList);
    19. }

    执行结果如下:

    5. MybatisPlus的常用注解

    5.1 @TableName

    为解决实体类与表名不一致的情况下能够找到对应的数据库表,mybatisPlus提供了@TableName注解。 

    如果数据库表名都是按照统一的命名方式进行命名(比如tb_xxx),这时候无需在每个实体类上都加入此注解,只需在yml文件配置表名前缀即可。

    5.2 @TabeId

    mybatisPlus会将每个表的id默认认为是主键如果表的id与实体类的id不一致的情况下会导致错误。

    假设数据库中表的主键为uid,实体类中的表的主键为id,此时使用@TabeId的value属性将两者保持一致即可。

    我们知道,在添加对象数据时id是默认使用雪花算法来生成id的,现在如果想要实现自动递增需要使用type属性。

    首先我们需要将表中的id的自动递增选项勾选。然后配置属性type自动递增即可。

    全局配置主键生成策略

    同样当我们对每个表的id都进行了@TabeId配置并想都想让其进行自动递增此时需要在配置文件中配置主键的自增策略。

    1. mybatis-plus:
    2. configuration:
    3. # 控制台日志打印
    4. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    5. global-config:
    6. db-config:
    7. # 配置表名前缀
    8. table-prefix: t_
    9. # 全局配置主键生成策略
    10. id-type: auto

    5.3 @TabeFiled

    与id处理一致,如果类中的字段名称与表中的字段名不一致的情况下使用@TabeFiled将两者进行对应。

    当然,字段名不一致mybatisPlus有默认的对应方式,就是默认下划线会转换为驼峰命名法。

    例如表中的姓名字段为user_name,类中的姓名字段为userName两者不会冲突。如果是name就必须使用@TabeFiled注解了。

    5.4 @TableLogic

    为了使删除的数据容易恢复,mybatisPlus提供了逻辑删除的方式。

    在表中添加字段is_delete后,实体类也需要添加对应变量,并加上@TableLogic注解

    1. @Data
    2. // 配置此注解可以使实体类与表名保持一致
    3. @TableName("t_user")
    4. public class User {
    5. @TableId(value = "uid")
    6. private Long id;
    7. private Integer age;
    8. @TableField("user_name")
    9. private String name;
    10. private String email;
    11. @TableLogic
    12. private Integer isDelete;
    13. }

    测试按照前面的方法再走一遍即可。

    7. 条件构造器介绍

    上面我们测试的是简单的增删改查,我们知道有的SQL查询需要复杂的查询条件。

    所以mybatisPlus给我们提供了Wrapper这个最顶端抽象类父类。它所包含的子类如下图所示:

    • AbstractWrapper:用于查询条件的封装,封装where条件。
    • QueryWrapper:查询条件封装。
    • UpdateWrapper:修改条件封装
    • LambdaUpdateWrapper:使用Lambda语法进行更新条件封装。
    • LambdaQueryWrapper:使用Lambda语法进行查询条件的封装。

    7.1 QueyWrapper查询条件组装

    对于多条件的复杂查询我们可以通过构造QueryWrpper对象条件。

    比如要查用户表中名字包含s,并且年龄在20到23之间,邮箱不为空的用户。

    1. @Test
    2. public void testQueryWrapperUser() {
    3. // 构造查询条件
    4. QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    5. // 查用户表中名字包含s,并且年龄在20到23之间,邮箱不为空的用户。
    6. queryWrapper.like("user_name", "s")
    7. .between("age", "20", "23")
    8. .isNotNull("email");
    9. List<User> users = userMapper.selectList(queryWrapper);
    10. users.forEach(System.out::println);
    11. }

    执行如下:

    7.2 QueyWrapper组装排序条件

    在上述例子中,我们将其加入年龄升序,id降序排序的条件。

    1. @Test
    2. public void testQueryWrapperUser() {
    3. // 构造查询条件
    4. QueryWrapper queryWrapper = new QueryWrapper<>();
    5. // 查用户表中名字包含s,并且年龄在20到23之间,邮箱不为空的用户。
    6. queryWrapper.like("user_name", "s")
    7. .between("age", "20", "23")
    8. .isNotNull("email")
    9. .orderByDesc("age")
    10. .orderByDesc("id");
    11. List users = userMapper.selectList(queryWrapper);
    12. users.forEach(System.out::println);
    13. }

    执行如下:

    7.3 QueryWrapper组装删除条件

    与查询条件一致,使用QueryWrapper构造删除条件:删除邮箱为空的用户。 

    1. @Test
    2. public void testQueryWrapperDelUser() {
    3. // 构造删除条件
    4. QueryWrapper queryWrapper = new QueryWrapper<>();
    5. // 删除邮箱为空的用户
    6. queryWrapper.isNull("email");
    7. int i = userMapper.delete(queryWrapper);
    8. System.out.println(i);
    9. }

    执行如下:

    7.4 QueyWrapper组装修改条件

    构造更新条件将邮箱为空的用户,年龄修改为45。

    代码逻辑很简单主要就是在更新对象的时候使用update方法将更新的对象传入。

    1. @Test
    2. public void testQueryWrapperDelUser() {
    3. // 构造更新条件 将邮箱为空的用户,年龄修改为45
    4. QueryWrapper queryWrapper = new QueryWrapper<>();
    5. queryWrapper.isNull("email");
    6. User user = new User();
    7. user.setAge(45);
    8. int i = userMapper.update(user, queryWrapper);
    9. System.out.println(i);
    10. }

    7.5 UpdateWrapper组装修改条件

    上面通过了QueryWrapper进行修改条件的封装,此外也可以通过UpdateWrapper进行修改条件的封装。

    1. @Test
    2. public void testUpdateWrapperDelUser() {
    3. // 构造更新条件 将邮箱为空的用户,年龄修改为46
    4. UpdateWrapper updateWrapper = new UpdateWrapper<>();
    5. updateWrapper.set("age",48).isNull("email");
    6. userMapper.update(null,updateWrapper);
    7. }

    请自行测试。

    8. LambdaQueryWrapper与LambdaUpdateWrapper

    在此之前,我们在构造查询或者修改条件的时候,都是直接去写表中的字段名,这样很容易出错,所以使用LambdaQueryWrapperLambdaUpdateWrapper去直接调用对象字段即可。

    7.2使用LambdaQueryWrapper进行改造:

    1. @Test
    2. public void testQueryWrapperUser() {
    3. // 构造查询条件
    4. LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>();
    5. lambdaQueryWrapper.like(User::getName, "s")
    6. .between(User::getAge, "20", "23")
    7. .isNotNull(User::getEmail)
    8. .orderByDesc(User::getAge)
    9. .orderByDesc(User::getId);
    10. List users = userMapper.selectList(lambdaQueryWrapper);
    11. users.forEach(System.out::println);
    12. }

    7.5使用LambdaUpdateWrapper进行改造:

    1. @Test
    2. public void testUpdateWrapperDelUser() {
    3. // 构造更新条件 将邮箱为空的用户,年龄修改为46
    4. LambdaUpdateWrapper lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
    5. lambdaUpdateWrapper.set(User::getAge,"78").isNull(User::getEmail);
    6. userMapper.update(null,lambdaUpdateWrapper);
    7. }

    9. LambdaQueryWrapper分页功能

    9.1 配置分页插件

    面对数据过多,页面展示数据有限,mybatisPlus提供了分页插件功能。首先需要进行配置类进行配置。

    MybatisPlusConfig.java

    1. package com.jektong.mybatisplus.config;
    2. import com.baomidou.mybatisplus.annotation.DbType;
    3. import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
    4. import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
    5. import org.springframework.context.annotation.Bean;
    6. import org.springframework.context.annotation.Configuration;
    7. import javax.print.DocFlavor;
    8. /**
    9. * @author jektong
    10. * @date 2022年11月11日 23:50
    11. */
    12. @Configuration
    13. public class MybatisPlusConfig {
    14. @Bean
    15. public MybatisPlusInterceptor mybatisPlusInterceptor(){
    16. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    17. // 配置数据源:mysql
    18. interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    19. return interceptor;
    20. }
    21. }

    配置完分页插件后通过Page对象来完成分页:

    1. @Test
    2. public void testPageUser() {
    3. // 当前1页显示2条数据
    4. Page pageUsers = new Page<>(1,2);
    5. // 查询数据
    6. userMapper.selectPage(pageUsers,null);
    7. System.out.println(pageUsers);
    8. }
  • 相关阅读:
    广州大学2023-2024学年第一学期《计算机网络》A卷
    使用股票量化交易接口需要具备怎么样的心态
    Spring Boot开发之参数处理
    VR数字党建:红色文化展厅和爱国主义教育线上线下联动
    go Cobra命令行工具入门
    mac(M1)卸载miniconda3
    广域网技术——SR-MPLS隧道保护技术
    Class Semantics-based Attention for Action Detection CSA论文阅读笔记
    通过提示工程将化学知识整合到大型语言模型中
    交叉验证太重要了!
  • 原文地址:https://blog.csdn.net/qq_41857955/article/details/127625978