• [Mybatis-Plus笔记] MybatisPlus-01-入门案例与基本CRUD


    本文主要参照 Mybatis-Plus 官网中的入门案例完成,只是官网中用的是 h2 数据库,本文用 mysql
    官网地址:https://baomidou.com/pages/226c21/

    一、项目构建

    本文中在 SpringBoot 项目中使用 Mybatis-Plus,苞米豆官网也提供了 SpringMVC 项目使用 Mybatis-Plus 的源码,可以自行查看:Spring MVC 快速启动示例

    1. 构建 SpringBoot 项目

    正常创建项目即可,起始依赖只需要 MySQL Driver,其他的都不需要,文中所用 SpringBoot 版本为 2.7.3

    在这里插入图片描述

    项目构建好后,pom.xml 中应该已经有了 spring-boot-starter,mysql-connector-java,和 spring-boot-starter-test 三个依赖,接下来只需把 Mybatis-Plus 相关依赖加入即可

    2. Maven依赖

    导入 mybatis-plus-boot-starter 的坐标

    <dependency>
        <groupId>com.baomidougroupId>
        <artifactId>mybatis-plus-boot-starterartifactId>
        <version>3.5.2version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    mybatis-plus-boot-starter 中包含有 mybatis-plus,而其中又包含 mybatis,mybatis-spring 等 Mybatis 的相关依赖,所以不用再手动导入其他依赖了,只需这一个即可

    另外,Mybatis-Plus 是配合 Mybatis 工作的,如果自己导入了其他的 Mybatis 版本,也许会发生不必要的冲突

    二、数据库的准备

    本文中的表结构和数据与官网给出的样例相同,但增加了主键 id 的自增属性

    1. 新建表

    DROP TABLE IF EXISTS user;
    
    CREATE TABLE user
    (
        id BIGINT(20) NOT NULL AUTO_INCREMENT 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)
    );
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2. 添加数据

    DELETE FROM user;
    
    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');
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3. yml 配置数据库信息

    在 resource 文件夹下新建 application.yml 文件,写入下面的数据

    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/mp_db	# mp_db 为数据库名称
        username: root
        password: "123456"  # 纯数字密码要双引号包裹
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    三、实体类与映射接口

    1. 编写 User 类

    User 类用于接收从数据库中查询来的数据,每一行就是一个 User 实例

    public class User {
        private Long id;
        private String name;
        private int age;
        private String email;
    
    	// 省略了 getter, setter, toString 等方法
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    如果你导入了 lombok 依赖,在类上注解 @Data 就可以省去编写 bean 类的基本方法

    [补充]

    • 实体类中的成员变量名应该与数据库中的列名保持一致,可以有大小写的区别

    2. 编写 UserMapper 映射接口

    就是 Mybati 中的映射接口,但继承了 BaseMapper 接口
    BaseMapper 是一个泛型接口,需要将 User 实体类放进去

    public interface UserMapper extends BaseMapper<User> {
    }
    
    • 1
    • 2

    暂时不需要写任何方法

    3. 使 Spring 扫描到映射接口

    (1)注解 @MapperScan

    给 SpringBoot 启动类注解 @MapperScan,使其能扫描到映射接口

    @SpringBootApplication
    @MapperScan("com.mzz.mapper")	// UserMapper 所在的包
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    自动装配时 IDEA 会报一个错误,但不影响运行,如果不想看见报错的话,可以给映射接口加上注解 @Repository

    @Repository
    public interface UserMapper extends BaseMapper<User> {
    }
    
    • 1
    • 2
    • 3

    (2)注解 @Mapper

    给映射接口加上注解 @Mapper 即可,可以不注解 @MapperScan

    @Mapper
    public interface UserMapper extends BaseMapper<User> {
    }
    
    • 1
    • 2
    • 3

    四、测试基本CRUD操作

    编写测试类

    类中要用 UserMapper 定义一个实例,并注解 @Autowired 进行自动装配,接下来的测试都通过调用实例中的方法来完成

    @SpringBootTest
    public class MybatisPlusTest {
    
        @Autowired
        UserMapper userMapper;
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在 UserMapper 映射接口中,没有写任何方法或者 SQL 语句,但是它继承了 BaseMapper 中的方法,下面的哪些基本的 CRUD 操作都是通过调用这些方法完成的

    1. 查询所有 selectList( )

    BaseMapper 接口中的 selectList( ) 方法,参数是一个条件选择器
    暂时将参数设为 null,Mybatis-Plus 就会查询所有行并返回一个 List

    @SpringBootTest
    public class MybatisPlusTest {
    
        @Autowired
        UserMapper userMapper;
    
        @Test
        void testSelectAll() {
            List<User> users = userMapper.selectList(null);
            System.out.println(users);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2. 按 id 查询 selectById( )

    selectById( ) 方法,参数是一个表示 id 的值

    @SpringBootTest
    public class MybatisPlusTest {
    
        @Autowired
        UserMapper userMapper;
        
        @Test
        void testSelectById() {
            User user = userMapper.selectById(1);
            System.out.println(user);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    3. 插入数据 insert( )

    insert( ),参数是一个实体类的实例,返回影响的行数,成功为 1,失败为 0

    @SpringBootTest
    public class MybatisPlusTest {
    
        @Autowired
        UserMapper userMapper;
    
        @Test
        void testInsert() {
            User user = new User(null, "Alice", 17, "12138@outlook.com");
            int ret = userMapper.insert(user);
            System.out.println(ret == 1 ? "插入成功!" : "插入失败,请检查 id 是否已被使用!");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    [补充]

    • 上例中 user 实例 id 为 null,但插入数据后 id 会被填充为数据库自增得出的 id。所以多次插入同一实例时,要小心主键重复问题

    处理自增 id

    像上例中运行以后,来到数据库可以发现数据是插入了,但这个自增的 id 似乎不太正常,它实在太大了,不是预期中的 6

    在这里插入图片描述

    解决方法很简单,在实体类的 id 成员变量上加上 @TableId 注解,并设置 type 为 IdType.AUTO

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        @TableId(type = IdType.AUTO)
        private Long id;
        private String name;
        private int age;
        private String email;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    如此配置后再次添加数据,你也许发现新增的 id 依然是一个很大的值,那是因为配置前插入的 id 已经将表的自增值提升到了那么大,请重新建表后再试,或者在 Navicat 中找到 设计表-选项-自动递增 修改其值即可(注意先删除 id 较大的那一行)

    在这里插入图片描述

    4. 按 id 删除 deleteById( )

    deleteById( ),参数是表示 id 的值,返回影响的行数,成功为 1,失败为 0

    @SpringBootTest
    public class MybatisPlusTest {
    
        @Autowired
        UserMapper userMapper;
        
        @Test
        void testDeleteById() {
            long id = 100;
            int ret = userMapper.deleteById(id);
            System.out.println(ret == 1 ? "删除成功!" : "删除失败,请检查 id 是否准确!");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    5. 按 id 更新数据 updateById( )

    updateById( ) 方法,参数是一个实体类的实例,数据库中 id 与实例 id 相同的行将会被更新

    返回影响的行数,成功为 1,失败为 0,即便更新后的数据与更新前相同,也会返回 1

    @SpringBootTest
    public class MybatisPlusTest {
    
        @Autowired
        UserMapper userMapper;
        
        @Test
        void testUpdate() {
            User user = new User(3L, "Sandy", 21, "10001@qq.com");
            int ret = userMapper.updateById(user);
            System.out.println(ret == 1 ? "更新成功!" : "更新失败,请检查 id 是否准确!");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
  • 相关阅读:
    label studio 结合 MMDetection 实现数据集自动标记、模型迭代训练的闭环
    33. 搜索旋转排序数组 ●● & 81. 搜索旋转排序数组 II ●●
    极市直播丨南京理工大学魏秀参、沈阳:大规模细粒度图像检索
    SpringMVC的拦截器(Interceptor)
    【Spring】AOP进阶-JoinPoint和ProceedingJoinPoint详解
    2023-11-17 服务器开发-性能分析-intel-vtune-安装
    Flink核心API之DataStream
    对于相对规范的服务API应如何实现
    Vue2+Vue3基础入门到实战项目全套教程的学习笔记
    新手怎么做小说推文和短剧推广怎么申请授权
  • 原文地址:https://blog.csdn.net/Cey_Tao/article/details/126764720