MyBatis-Plus环境搭建和单表的curd操作

目录

  • [1 环境搭建](#1 环境搭建)
    • [1.1 创建工程并引入依赖](#1.1 创建工程并引入依赖)
    • [1.2 编写启动类](#1.2 编写启动类)
    • [1.3 编写实体类与 Mapper 接口](#1.3 编写实体类与 Mapper 接口)
    • [1.4 编写配置文件](#1.4 编写配置文件)
    • [1.5 配置日志输出](#1.5 配置日志输出)
    • [1.6 测试是否整合成功](#1.6 测试是否整合成功)
  • [2 基本 CRUD 操作](#2 基本 CRUD 操作)
    • [2.1 插入操作](#2.1 插入操作)
    • [2.2 删除操作](#2.2 删除操作)
      • [2.2.1 根据 id 删除](#2.2.1 根据 id 删除)
      • [2.2.2 根据 id 批量删除](#2.2.2 根据 id 批量删除)
      • [2.2.3 根据 Map 条件删除](#2.2.3 根据 Map 条件删除)
    • [2.3 修改操作](#2.3 修改操作)
      • [2.3.1 根据 id 修改](#2.3.1 根据 id 修改)
      • [2.3.2 根据条件修改(QueryWrapper)](#2.3.2 根据条件修改(QueryWrapper))
      • [2.3.3 根据条件修改(UpdateWrapper)](#2.3.3 根据条件修改(UpdateWrapper))
    • [2.4 查询操作](#2.4 查询操作)
      • [2.4.1 根据 id 查询](#2.4.1 根据 id 查询)
      • [2.4.2 根据 id 批量查询](#2.4.2 根据 id 批量查询)
      • [2.4.3 根据 Map 条件查询](#2.4.3 根据 Map 条件查询)
      • [2.4.4 查询所有数据](#2.4.4 查询所有数据)

1 环境搭建

1.1 创建工程并引入依赖

创建 SpringBoot 工程,在 pom.xml 中引入以下依赖:

xml 复制代码
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.2</version>
    <relativePath/>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <!-- SpringBoot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- SpringBoot 核心 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <!-- SpringBoot 测试 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- MyBatis-Plus -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.1</version>
    </dependency>

    <!-- Lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

    <!-- MySQL 驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

1.2 编写启动类

java 复制代码
@SpringBootApplication
@MapperScan(basePackages = "com.xq.mapper")
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

@MapperScan 用于指定 Mapper 接口所在的包路径,启动时会自动扫描并注册到 Spring 容器中。

1.3 编写实体类与 Mapper 接口

实体类 User:

java 复制代码
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

Mapper 接口:

java 复制代码
public interface UserMapper extends BaseMapper<User> {
}

继承 BaseMapper<User> 后,即可直接使用 MyBatis-Plus 内置的 CRUD 方法,无需编写 XML 映射文件。

1.4 编写配置文件

application.yml 中配置数据源:

yaml 复制代码
spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
    username: root
    password: your_password

注意事项:

驱动类 driver-class-name

  • Spring Boot 2.0(内置 JDBC 5 驱动):使用 com.mysql.jdbc.Driver
  • Spring Boot 2.1 及以上(内置 JDBC 8 驱动):使用 com.mysql.cj.jdbc.Driver

使用错误的驱动类不会导致程序报错,但会在控制台输出 WARN 信息。

连接地址 url

  • MySQL 5.7:jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
  • MySQL 8.0:jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false

MySQL 8.0 必须指定 serverTimezone,否则会报错:

java.sql.SQLException: The server time zone value 'xxx' is unrecognized or represents more

1.5 配置日志输出

MyBatis-Plus 默认不会在控制台打印 SQL 语句。添加以下配置可以开启日志,方便调试时观察实际执行的 SQL:

yaml 复制代码
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

1.6 测试是否整合成功

java 复制代码
@SpringBootTest
public class MybatisPlusTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelectList() {
        // selectList(null) 表示无条件查询所有记录
        userMapper.selectList(null).forEach(System.out::println);
    }
}

运行测试方法,如果控制台能正常输出数据库中的记录,说明 SpringBoot 整合 MyBatis-Plus 已经成功。


2 基本 CRUD 操作

MyBatis-Plus 在 BaseMapper 中封装了常用的 CRUD 方法,以下逐一演示。

2.1 插入操作

使用 insert() 方法插入一条记录:

java 复制代码
@Test
public void testInsert() {
    User user = new User(null, "张三", 23, "zhangsan@qq.com");
    // 执行SQL: INSERT INTO user (id, name, age, email) VALUES (?, ?, ?, ?)
    int result = userMapper.insert(user);
    System.out.println("受影响行数:" + result);
    System.out.println("id自动获取:" + user.getId());
}

执行后获取到的 id 为类似 1778676561893969922 的长整型数值。这是因为 MyBatis-Plus 默认使用雪花算法(Snowflake)生成主键 id ,而非数据库自增。如果需要使用自增策略,可以通过 @TableId(type = IdType.AUTO) 注解来指定。

2.2 删除操作

MyBatis-Plus 提供了 3 种删除方式。

2.2.1 根据 id 删除

deleteById():根据主键 id 删除单条记录。

java 复制代码
@Test
public void testDeleteById() {
    // 执行SQL: DELETE FROM user WHERE id=?
    int result = userMapper.deleteById(1778676561893969922L);
    System.out.println("受影响行数:" + result);
}
2.2.2 根据 id 批量删除

deleteBatchIds():传入 id 集合,批量删除多条记录。

java 复制代码
@Test
public void testDeleteBatchIds() {
    // 执行SQL: DELETE FROM user WHERE id IN (?, ?, ?)
    List<Long> idList = Arrays.asList(1L, 2L, 3L);
    int result = userMapper.deleteBatchIds(idList);
    System.out.println("受影响行数:" + result);
}
2.2.3 根据 Map 条件删除

deleteByMap():将删除条件封装为 Map,Map 中的每个键值对会作为 WHERE 子句中的等值条件,多个条件之间用 AND 连接。

java 复制代码
@Test
public void testDeleteByMap() {
    // 执行SQL: DELETE FROM user WHERE name = ? AND age = ?
    Map<String, Object> map = new HashMap<>();
    map.put("age", 23);
    map.put("name", "张三");
    int result = userMapper.deleteByMap(map);
    System.out.println("受影响行数:" + result);
}

2.3 修改操作

MyBatis-Plus 提供了 2 种更新方式。

2.3.1 根据 id 修改

updateById():根据实体对象的 id 字段定位记录,将非 null 字段更新到数据库。

java 复制代码
@Test
public void testUpdateById() {
    User user = new User(4L, "admin", 22, null);
    // 执行SQL: UPDATE user SET name=?, age=? WHERE id=?
    // 注意:email 为 null,不会出现在 SET 子句中
    int result = userMapper.updateById(user);
    System.out.println("受影响行数:" + result);
}
2.3.2 根据条件修改(QueryWrapper)

update(entity, wrapper):第一个参数是包含更新字段的实体对象,第二个参数是条件构造器。

java 复制代码
@Test
public void testUpdateByWrapper() {
    User user = new User();
    user.setAge(22);
    user.setEmail("admin@qq.com");

    // 构造更新条件
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("id", 4L);

    // 执行SQL: UPDATE user SET age=?, email=? WHERE (id = ?)
    int result = userMapper.update(user, wrapper);
    System.out.println("受影响行数:" + result);
}
2.3.3 根据条件修改(UpdateWrapper)

UpdateWrapper 可以同时设置更新条件和更新字段,不需要再传入实体对象:

java 复制代码
@Test
public void testUpdateByUpdateWrapper() {
    UpdateWrapper<User> wrapper = new UpdateWrapper<>();
    wrapper.eq("id", 4L)
           .set("age", 28)
           .set("email", "admin@163.com");

    // 执行SQL: UPDATE user SET age=?, email=? WHERE (id = ?)
    int result = userMapper.update(null, wrapper);
    System.out.println("受影响行数:" + result);
}

QueryWrapper vs UpdateWrapper:

  • QueryWrapper:需要配合实体对象使用,更新字段由实体的非 null 属性决定。
  • UpdateWrapper:通过 .set() 方法直接指定更新字段,不依赖实体对象,写法更灵活。

2.4 查询操作

MyBatis-Plus 提供了多种查询方式。

2.4.1 根据 id 查询

selectById():根据主键查询单条记录。

java 复制代码
@Test
public void testSelectById() {
    // 执行SQL: SELECT id, name, age, email FROM user WHERE id=?
    User user = userMapper.selectById(4L);
    System.out.println(user);
}
2.4.2 根据 id 批量查询

selectBatchIds():传入 id 集合,查询多条记录。

java 复制代码
@Test
public void testSelectBatchIds() {
    // 执行SQL: SELECT id, name, age, email FROM user WHERE id IN (?, ?)
    List<Long> idList = Arrays.asList(4L, 5L);
    List<User> list = userMapper.selectBatchIds(idList);
    list.forEach(System.out::println);
}
2.4.3 根据 Map 条件查询

selectByMap():将查询条件封装为 Map,与 deleteByMap() 用法一致。

java 复制代码
@Test
public void testSelectByMap() {
    // 执行SQL: SELECT id, name, age, email FROM user WHERE name = ? AND age = ?
    Map<String, Object> map = new HashMap<>();
    map.put("age", 20);
    map.put("name", "Jack");
    List<User> list = userMapper.selectByMap(map);
    list.forEach(System.out::println);
}
2.4.4 查询所有数据

selectList(null):传入 null 表示不附加任何条件,查询全部记录。

java 复制代码
@Test
public void testSelectList() {
    // 执行SQL: SELECT id, name, age, email FROM user
    List<User> list = userMapper.selectList(null);
    list.forEach(System.out::println);
}

本文介绍了 SpringBoot 整合 MyBatis-Plus 的环境搭建流程,以及 BaseMapper 提供的基本 CRUD 操作。下一篇将介绍 MyBatis-Plus 的通用 Service 层封装