← 返回心得列表

Spring Boot 集成 MyBatis 的完整实践

2026-09-27 Java
从依赖引入到 Mapper XML 编写,一套可复制的集成流程。

MyBatis 是 Java 生态里最常用的 ORM 之一,和 Spring Boot 集成非常简单。这篇记录一套可以直接复制的实践。

引入依赖

在 pom.xml 中加入 mybatis-spring-boot-starter 和对应的数据库驱动。

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.3.2</version>
</dependency>

配置文件

在 application.yml 里配置数据源和 Mapper 扫描。

mybatis:
  type-aliases-package: com.example.entity
  mapper-locations: classpath:mapper/*.xml

编写 Mapper

接口负责声明方法,XML 负责写 SQL,两者通过 namespace 绑定。

@Mapper
public interface UserMapper {
    User findById(Long id);
}

小结

MyBatis 的优势是 SQL 完全可控,复杂查询写起来比 JPA 直观。适合喜欢手写 SQL 的团队。