Spring Boot 整合 MyBatis

Spring Boot 整合 MyBatis

MyBatis 是一个半自动化的 ORM 框架,所谓半自动化是指 MyBatis 只支持将数据库查出的数据映射到 POJO 实体类上,而实体到数据库的映射则需要我们自己编写 SQL 语句实现,相较于Hibernate 这种完全自动化的框架,Mybatis 更加灵活,我们可以根据自身的需求编写 sql 语句来实现复杂的数据库操作。

引入依赖

Spring Boot 整合 MyBatis 的第一步,就是在项目的 pom.xml 中引入 mybatis-spring-boot-starter 的依赖,示例代码如下。

1
2
3
4
5
6
<!--引入 mybatis-spring-boot-starter 的依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>

配置 MyBatis

在 Spring Boot 的配置文件(application.properties/yml)中对 MyBatis 进行配置,例如指定 mapper.xml 的位置、实体类的位置、是否开启驼峰命名法等等,示例代码如下。

1
2
3
4
5
6
7
8
9
10
# MyBatis 配置
mybatis:
# 指定 mapper.xml 的位置
mapper-locations: classpath:mybatis/mapper/*.xml
# 扫描实体类的位置,在此处指明扫描实体类的包,
# 在 mapper.xml 中就可以不写实体类的全路径名
type-aliases-package: com.felixcjy
configuration:
# 默认开启驼峰命名法,可以不用设置该属性
map-underscore-to-camel-case: true

注意:使用 MyBatis 时,必须配置数据源信息,例如数据库 URL、数据库用户型、数据库密码和数据库驱动等。

创建实体类

在指定的数据库内创建一个 user 表,并插入一些数据,如下表。

id user_id user_name
1 001 admin
2 002 user
1
2
3
4
5
6
public class User {
private Integer id;
private String userId;
private String userName;
// 方法略
}

创建 Mapper 接口

在 com.felixcjy.mapper 中创建一个 UserMapper 接口,并在该类上使用 @Mapper 注解,代码如下。

1
2
3
4
5
6
7
import net.biancheng.www.bean.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
//通过用户名密码查询用户数据
User getByUserNameAndPassword(User user);
}

当 mapper 接口较多时,我们可以在 Spring Boot 主启动类上使用 @MapperScan 注解扫描指定包下的 mapper 接口,而不再需要在每个 mapper 接口上都标注 @Mapper 注解。

创建 Mapper 映射文件

在配置文件 application.properties/yml 通过 mybatis.mapper-locations 指定的位置中创建 UserMapper.xml,代码如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.biancheng.www.mapper.UserMapper">
<resultMap id="BaseResultMap" type="User">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="user_id" jdbcType="VARCHAR" property="userId"/>
<result column="user_name" jdbcType="VARCHAR" property="userName"/>
<result column="password" jdbcType="VARCHAR" property="password"/>
<result column="email" jdbcType="VARCHAR" property="email"/>
</resultMap>
<sql id="Base_Column_List">
id, user_id, user_name, password, email
</sql>
<!--根据用户名密码查询用户信息-->
<!--application.yml 中通过 type-aliases-package 指定了实体类的为了,因此-->
<select id="getByUserNameAndPassword" resultType="User">
select *
from user where user_name = #{userName,jdbcType=VARCHAR}
and password = #{password,jdbcType=VARCHAR}
</select>
</mapper>

使用 Mapper 进行开发时,需要遵循以下规则:

  • mapper 映射文件中 namespace 必须与对应的 mapper 接口的完全限定名一致。
  • mapper 映射文件中 statement 的 id 必须与 mapper 接口中的方法的方法名一致
  • mapper 映射文件中 statement 的 parameterType 指定的类型必须与 mapper 接口中方法的参数类型一致。
  • mapper 映射文件中 statement 的 resultType 指定的类型必须与 mapper 接口中方法的返回值类型一致。