mybatis-plus从入门到入土(一):快速开始

发布于:2025-06-30 ⋅ 阅读:(20) ⋅ 点赞:(0)

​ 朋友们, 大家好, 从今天开始我想开一个系列博客。名字起的比较随意就叫Mybatis-Plus从入门到入土, 这系列博客的定位是从基础使用开始, 然后逐步深入全面的了解Mybatis-Plus框架, 写这个博客的主要原因是工作中经常用到Mybatis-Plus框架, 因而对这个框架相对比较了解一些, 顺便在写作的过程中对自身知识查漏补缺, 欢迎小伙伴和我一同步入Mybatis-Plus之旅, 我们马上起飞。

快速开始

我们从Mybatis-Plus官网的快速开始一步步的学习这个框架。

引入Mybatis-Plus相关依赖

对于SpringBoot项目来说, Mybatis-Plus的依赖相对简单, 只有一个starter。这里我基于Spring Boot2mybatis-plus 3.5.12, 今后的学习也基于该版本。

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.12</version>
</dependency>

配置

  • application.yml 配置文件中添加 H2 数据库的相关配置:
# DataSource Config
spring:
  datasource:
    driver-class-name: org.h2.Driver
    username: root
    password: test
  sql:
    init:
      schema-locations: classpath:db/schema-h2.sql
      data-locations: classpath:db/data-h2.sql

这里基于H2数据库, 如果小伙伴手头有其他数据库也可以使用, sql-init中指定的是数据库的表结构示例数据。关于mybatis-plus具体支持哪些数据库可以参考https://baomidou.com/introduce/。

  • 在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:
@SpringBootApplication
@MapperScan("com.example.mybatispluslearning.mapper")
public class MybatisPlusLearningApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusLearningApplication.class, args);
    }

}

编码

创建一个User类

@Data
@TableName("sys_user")
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

创建一个UserMapper接口, 这个类继承了mybatis-plus提供的BaseMapper接口

public interface UserMapper extends BaseMapper<User> {

}

测试

@SpringBootTest
public class SampleTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List<User> userList = userMapper.selectList(null);
        Assert.isTrue(5 == userList.size(), "");
        userList.forEach(System.out::println);
    }

}

在这里插入图片描述

好了, 小伙伴们, 第一讲就讲完了, 敬请收看第二讲。