# SpringBoot3教程 - 23 SpringBoot集成Mybatis

下面介绍一下在 SpringBoot 中集成 Mybatis。

# 23.1 快速集成

# 1 准备数据库和表数据

# 建库
CREATE DATABASE IF NOT EXISTS foooor_db;
USE foooor_db;

# 建表
CREATE TABLE tb_user(
  id INT NOT NULL AUTO_INCREMENT COMMENT 'ID',
  username varchar(64) NOT NULL COMMENT '用户名',
  age tinyint unsigned DEFAULT NULL COMMENT '年龄',
  create_time datetime DEFAULT NULL COMMENT '创建时间',
	PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';

# 插入数据
INSERT INTO tb_user (id, username, age, create_time) VALUES 
(1, 'doubi', 25, NOW()),
(2, 'niubi', 30, NOW()),
(3, 'shabi', 22, NOW()),
(4, 'erbi', 28, NOW()),
(5, 'shibi', 35, NOW());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 2 创建项目

按照HelloWorld中的介绍,直接创建就好了,我这里项目名为 hello-mybatis

准备好主启动类。

# 3 pom添加依赖

主要是添加 mybatis 的 starter 依赖和 mysql 驱动依赖。

<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.3.0</version>
    </parent>

    <groupId>com.foooor</groupId>
    <artifactId>hello-mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>hello-mybatis</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- 导入web项目的依赖,版本是spring-boot-starter-parent控制的 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <!-- 配置文件处理器,配置文件可以有提示 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

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

        <!-- mysql驱动依赖!!! -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.4.0</version>
        </dependency>

        <!-- mybatis依赖!!! -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

# 4 编写配置文件

在 application.yaml 中添加数据源配置和mybatis的配置,如下:

# 数据源配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/foooor_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT
    username: root
    password: 123456
    hikari:
      minimum-idle: 5  # 最小空闲连接数
      maximum-pool-size: 10  # 最大活跃连接数
      idle-timeout: 30000  # 空闲连接生命周期,以毫秒为单位
      pool-name: HikariCP  # 连接池名称,主要用于记录日志和JMX管理,默认为生成的
      max-lifetime: 1800000  # 连接在连接池中允许存在的最长时间,默认为30分钟,以毫秒为单位
      connection-timeout: 30000  # 连接超时时间,以毫秒为单位


# mybaits配置
mybatis:
  # MyBatis Mapper所对应的XML文件位置
  mapper-locations: classpath*:/mapper/*Mapper.xml
  # 类型别名配置
  type-aliases-package: com.foooor.hellomybatis.pojo
  configuration:
    # 开启驼峰命名
    map-underscore-to-camel-case: true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

在 Spring Boot 中默认的连接池是 HikariCP 连接池。

下面编写pojo、mapper、service、controller。

# 5 编写pojo

编写与数据库映射的实体类。

User.java

package com.foooor.hellomybatis.pojo;

import lombok.Data;

import java.util.Date;

@Data
public class User {
    private String id;
    private String username;
    private Integer age;
    private Date createTime;
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 6 编写Mapper

编写 Mybatis 获取数据的 Mapper。

UserMapper.java,添加 @Mapper 注解

package com.foooor.hellomybatis.mapper;

import com.foooor.hellomybatis.pojo.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper {
    /**
     * 根据ID查询用户
     */
    User selectById(Integer id);

    /**
     * 插入用户
     */
    int insert(User user);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

src/main/resources 下创建 mapper 文件夹,并编写对应的 UserMapper.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">

<mapper namespace="com.foooor.hellomybatis.mapper.UserMapper">

    <!-- 根据id查询用户 -->
    <select id="selectById" resultType="User">
        SELECT * FROM tb_user
        WHERE id = #{id}
    </select>


    <!-- 插入用户 -->
    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO tb_user (username, age, create_time)
        VALUES (#{username}, #{age}, #{createTime})
    </insert>

</mapper>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 7 编写service

编写业务实现类service,和对应的service接口,通过 service 调用 mapper,获取和添加数据。

UserServiceImpl.java,添加@Service注解

package com.foooor.hellomybatis.service.impl;

import com.foooor.hellomybatis.mapper.UserMapper;
import com.foooor.hellomybatis.pojo.User;
import com.foooor.hellomybatis.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 通过ID查找用户
     */
    public User getUserById(Integer userId) {
        log.info("根据ID查找用户, userId:{}", userId);
        User user = userMapper.selectById(userId);
        return user;
    }

    /**
     * 保存用户
     */
    public User saveUser(String username, Integer age) {
        User user = new User();
        user.setUsername(username);
        user.setAge(age);
        user.setCreateTime(new Date());
        userMapper.insert(user);

        return user;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

对应的接口,IUserService.java

package com.foooor.hellomybatis.service;

import com.foooor.hellomybatis.pojo.User;

public interface IUserService {
    /**
     * 通过ID查找用户
     */
    User getUserById(Integer userId);

    /**
     * 保存用户
     */
    User saveUser(String username, Integer age);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 8 编写controller

通过接口调用 service,获取和添加数据。

UserController.java

package com.foooor.hellomybatis.controller;

import com.foooor.hellomybatis.pojo.User;
import com.foooor.hellomybatis.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 获取用户信息
     */
    @GetMapping("/{userId}")
    public User getById(@PathVariable("userId") Integer userId) {
        return userService.getUserById(userId);
    }

    /**
     * 添加用户
     */
    @GetMapping("/add") // 为了方便用get请求
    public User saveUser(@RequestParam("username") String username, @RequestParam("age") Integer age) {
        return userService.saveUser(username, age);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

为了测试方便,添加也使用了 Get 方式。

# 9 测试

请求接口添加数据:http://localhost:8080/user/add?username=doubi&age=13

请求接口获取数据:http://localhost:8080/user/1


# 10 项目结构