SpringBoot整合MyBatis完全指南
作者:步行cgn
引言
在 SSM(Spring + Spring MVC + MyBatis)时代,整合 MyBatis 需要在 XML 中配置 SqlSessionFactory、DataSource、事务管理器等多个 Bean,繁琐且容易出错。Spring Boot 通过 Starter 机制将这一切自动化,让整合变得极其简单。
一、核心依赖
Spring Boot 整合 MyBatis 需要引入两个核心依赖:
<dependencies>
<!-- Spring Boot Web Starter(包含 Spring MVC、内嵌 Tomcat 等) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis Spring Boot Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.3</version>
</dependency>
<!-- MySQL 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Lombok(可选,简化实体类) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>mybatis-spring-boot-starter 整合了 MyBatis 核心库、Spring 整合库(mybatis-spring)以及自动配置类,是整合的入口依赖。
二、配置文件
2.1 application.yml 基础配置
# 数据源配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8
username: root
password: 123456
# HikariCP 连接池配置(Spring Boot 2.x 默认使用 HikariCP)
hikari:
maximum-pool-size: 20
minimum-idle: 5
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
# MyBatis 配置
mybatis:
# Mapper XML 文件位置
mapper-locations: classpath:mapper/*.xml
# 实体类包路径(用于别名)
type-aliases-package: com.example.entity
# MyBatis 全局配置
configuration:
# 开启驼峰命名转换:数据库下划线 → Java 驼峰
map-underscore-to-camel-case: true
# 开启二级缓存
cache-enabled: true
# 开启延迟加载
lazy-loading-enabled: true
# 关闭激进加载
aggressive-lazy-loading: false
# 日志实现
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 自动映射行为(PARTIAL:只对非嵌套对象自动映射)
auto-mapping-behavior: partial
# 超时时间(秒)
default-statement-timeout: 30
# 允许 JDBC 生成主键
use-generated-keys: true2.2 基础配置的作用
| 配置项 | 作用 |
|---|---|
mapper-locations | 指定 Mapper XML 文件的位置,支持通配符 |
type-aliases-package | 实体类包路径,MyBatis 会自动为该包下的类注册别名(类名首字母小写) |
map-underscore-to-camel-case | 自动将数据库的 user_name 映射到 Java 的 userName |
log-impl | 指定日志实现,StdOutImpl 将 SQL 输出到控制台(开发环境常用) |
三、代码结构
3.1 项目结构
src/main/java/com/example/
├── Application.java # 启动类(含 @MapperScan)
├── controller/
│ └── UserController.java
├── service/
│ ├── UserService.java # 接口
│ └── impl/
│ └── UserServiceImpl.java # 实现类
├── mapper/
│ └── UserMapper.java # Mapper 接口
└── entity/
└── User.java # 实体类
src/main/resources/
├── application.yml
└── mapper/
└── UserMapper.xml # MyBatis XML 映射文件
3.2 启动类
package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.mapper") // 扫描 Mapper 接口所在的包
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@MapperScan 是 MyBatis-Spring 提供的注解,它会扫描指定包下的所有 Mapper 接口,为它们生成代理对象并注册到 Spring 容器中。
3.3 实体类
package com.example.entity;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class User {
private Long id;
private String username;
private String password;
private String email;
private Integer age;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
3.4 Mapper 接口
package com.example.mapper;
import com.example.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
// 如果使用了 @MapperScan,每个 Mapper 接口可以不写 @Mapper
// 但保留 @Mapper 可以让 IDE 识别,也能在非 @MapperScan 环境下工作
@Mapper
public interface UserMapper {
User selectById(@Param("id") Long id);
List<User> selectAll();
List<User> selectByCondition(@Param("username") String username,
@Param("age") Integer age);
int insert(User user);
int update(User user);
int deleteById(@Param("id") Long id);
int insertBatch(@Param("list") List<User> users);
}
方法参数与 XML 参数映射:
@Param 注解是多参数方法的关键,它将参数与 XML 中的 #{xxx} 对应起来。如果方法只有一个参数且不是集合或 Map 类型,可以不加 @Param,但建议始终加上以保持一致性。
返回值类型与 XML 结果映射:
方法返回值类型必须与 XML 中 resultType 或 resultMap 匹配。单条记录返回 User,多条返回 List<User>,插入/更新/删除返回 int。
3.5 Mapper XML 文件
<?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="com.example.mapper.UserMapper">
<!-- 基础字段列表(可复用) -->
<sql id="Base_Column_List">
id, username, password, email, age, create_time, update_time
</sql>
<!-- 结果映射 -->
<resultMap id="BaseResultMap" type="User">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="email" column="email"/>
<result property="age" column="age"/>
<result property="createTime" column="create_time"/>
<result property="updateTime" column="update_time"/>
</resultMap>
<!-- 根据 ID 查询 -->
<select id="selectById" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM user
WHERE id = #{id}
</select>
<!-- 查询所有 -->
<select id="selectAll" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM user
ORDER BY id DESC
</select>
<!-- 条件查询 -->
<select id="selectByCondition" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM user
<where>
<if test="username != null and username != ''">
AND username LIKE CONCAT('%', #{username}, '%')
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
<!-- 插入(返回自增主键) -->
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user (username, password, email, age, create_time)
VALUES (#{username}, #{password}, #{email}, #{age}, NOW())
</insert>
<!-- 批量插入 -->
<insert id="insertBatch" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user (username, password, email, age, create_time)
VALUES
<foreach collection="list" item="user" separator=",">
(#{user.username}, #{user.password}, #{user.email}, #{user.age}, NOW())
</foreach>
</insert>
<!-- 更新 -->
<update id="update">
UPDATE user
<set>
<if test="username != null and username != ''">username = #{username},</if>
<if test="password != null and password != ''">password = #{password},</if>
<if test="email != null and email != ''">email = #{email},</if>
<if test="age != null">age = #{age},</if>
update_time = NOW()
</set>
WHERE id = #{id}
</update>
<!-- 删除 -->
<delete id="deleteById">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>XML 命名规范:
namespace 必须与 Mapper 接口的全限定名完全一致。id 必须与接口方法名完全一致。如果使用 resultMap,需要在 XML 中定义 <resultMap>,并在 <select> 中通过 resultMap 属性引用。
四、Service 层使用 Mapper
4.1 Service 接口
package com.example.service;
import com.example.entity.User;
import java.util.List;
public interface UserService {
User getById(Long id);
List<User> listAll();
List<User> listByCondition(String username, Integer age);
void save(User user);
void batchSave(List<User> users);
void update(User user);
void deleteById(Long id);
}
4.2 Service 实现
package com.example.service.impl;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getById(Long id) {
return userMapper.selectById(id);
}
@Override
public List<User> listAll() {
return userMapper.selectAll();
}
@Override
public List<User> listByCondition(String username, Integer age) {
return userMapper.selectByCondition(username, age);
}
@Override
@Transactional
public void save(User user) {
userMapper.insert(user);
}
@Override
@Transactional
public void batchSave(List<User> users) {
userMapper.insertBatch(users);
}
@Override
@Transactional
public void update(User user) {
userMapper.update(user);
}
@Override
@Transactional
public void deleteById(Long id) {
userMapper.deleteById(id);
}
}
五、Controller 层
package com.example.controller;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userService.getById(id);
}
@GetMapping
public List<User> listAll() {
return userService.listAll();
}
@GetMapping("/search")
public List<User> search(@RequestParam(required = false) String username,
@RequestParam(required = false) Integer age) {
return userService.listByCondition(username, age);
}
@PostMapping
public void save(@RequestBody User user) {
userService.save(user);
}
@PostMapping("/batch")
public void batchSave(@RequestBody List<User> users) {
userService.batchSave(users);
}
@PutMapping
public void update(@RequestBody User user) {
userService.update(user);
}
@DeleteMapping("/{id}")
public void deleteById(@PathVariable Long id) {
userService.deleteById(id);
}
}
六、事务管理
Spring Boot 整合 MyBatis 后,事务管理由 Spring 的 DataSourceTransactionManager 负责。只要在 Service 方法上添加 @Transactional 注解即可。
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private InventoryMapper inventoryMapper;
@Transactional(rollbackFor = Exception.class)
public void createOrder(Order order) {
// 插入订单
orderMapper.insert(order);
// 扣减库存(如果失败,订单插入也会回滚)
inventoryMapper.decrease(order.getProductId(), order.getQuantity());
}
}
@Transactional 的传播行为和隔离级别与 Spring 标准用法一致。在 Spring Boot 中,数据源的自动配置会自动创建 DataSourceTransactionManager,无需额外配置。
七、整合原理:自动配置详解
mybatis-spring-boot-starter 的自动配置类 MybatisAutoConfiguration 在 Spring Boot 启动时做了三件核心工作:
1. 创建 SqlSessionFactory
检测到 classpath 中存在 SqlSessionFactory 类且容器中没有自定义的 SqlSessionFactory Bean 时,自动创建 SqlSessionFactoryBean 并初始化 SqlSessionFactory。它从 application.yml 读取 MyBatis 配置(mapper-locations、type-aliases-package 等),与 DataSource 一起构建。
2. 创建 SqlSessionTemplate
SqlSessionTemplate 是线程安全的 SqlSession 实现,所有 Mapper 方法最终都会通过它执行。它代替了手动管理的 SqlSession,让开发者无需关心会话的开启和关闭。
3. 扫描 Mapper 接口
@MapperScan 注解触发 MapperScannerConfigurer,它扫描指定包路径下的接口,每个接口生成一个 MapperFactoryBean。MapperFactoryBean 通过 SqlSessionTemplate 获取代理对象,当接口方法被调用时,代理对象将方法调用转发给 SqlSessionTemplate,由它执行 SQL。
核心组件关系:
DataSource→SqlSessionFactory→SqlSessionTemplate→MapperProxy→Mapper 方法调用SqlSessionFactory是重量级对象,全局唯一MapperScannerConfigurer是在BeanFactoryPostProcessor阶段执行的,早于 Bean 的实例化
八、常见问题与解决方案
1. Invalid bound statement (not found)
原因:XML 文件中的 namespace 或 id 与 Mapper 接口不匹配。
解决:
- 检查
namespace= 接口全限定名 - 检查
id= 接口方法名 - 检查
mapper-locations配置是否正确 - 检查 XML 文件是否在
target/classes目录中(Maven 资源过滤问题)
2. @Autowired 注入 Mapper 失败
原因:Mapper 接口未被 Spring 管理。
解决:
- 检查是否在启动类上添加了
@MapperScan - 检查
@MapperScan的包路径是否包含 Mapper 接口 - 或在 Mapper 接口上单独添加
@Mapper
3. 字段值为 null(下划线转驼峰失效)
原因:map-underscore-to-camel-case 未开启。
解决:在 application.yml 的 mybatis.configuration 中添加 map-underscore-to-camel-case: true
4. 懒加载异常(LazyInitializationException)
在 Spring 环境,需要确保懒加载在事务中完成,或在 OpenSessionInView 模式下完成。
@Transactional
public void getUserWithOrders(Long userId) {
User user = userMapper.selectById(userId);
// 在事务中访问懒加载的 orders
user.getOrders().size();
}
5. 事务不生效
检查:
- 是否在 Service 类上加了
@Service(Bean 被 Spring 管理) - 是否在方法或类上加了
@Transactional - 是否通过代理调用的(同一个类内部调用无效)
- 数据源是否支持事务(如使用了
@Transactional但数据源是 H2 内存数据库)
九、最佳实践总结
- 使用
@MapperScan集中扫描 Mapper:避免每个接口单独加@Mapper - 开启驼峰转换:
map-underscore-to-camel-case: true,省去大量字段映射配置 - 配置类型别名:
type-aliases-package让 XML 中可以直接写类名(首字母小写) - Mapper XML 统一放在
src/main/resources/mapper:与 Java 代码分离 - 事务注解放在 Service 层:保证多个 Mapper 操作在同一事务中
- SQL 输出到日志:开发环境开启
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl或配置logging.level.com.example.mapper=DEBUG - 实体类使用 Lombok:简化代码
- 批量操作使用
<foreach>:减少数据库连接开销 - 慎用 N+1 查询:一对多关联时注意
collection的懒加载和性能问题
以上就是SpringBoot整合MyBatis完全指南的详细内容,更多关于SpringBoot整合MyBatis指南的资料请关注脚本之家其它相关文章!
