1. 简介

MyBatis 是 Java 生态中广泛使用的开源框架之一,主要用于实现 SQL 数据库访问。

本文将介绍如何在 Spring 及 Spring Boot 中集成 MyBatis。

如果你对 MyBatis 还不熟悉,可以先参考我们的 MyBatis 入门教程,了解其基本用法。


2. 定义模型

我们从一个简单的 POJO 开始,这个类将贯穿全文:

public class Article {
    private Long id;
    private String title;
    private String author;

    // 构造函数、getter 和 setter 省略
}

对应的数据库建表语句如下(保存在 schema.sql 中):

CREATE TABLE IF NOT EXISTS `ARTICLES`(
    `id`          INTEGER PRIMARY KEY,
    `title`       VARCHAR(100) NOT NULL,
    `author`      VARCHAR(100) NOT NULL
);

再准备一个 data.sql 文件,用于初始化一条测试数据:

INSERT INTO ARTICLES
VALUES (1, 'Working with MyBatis in Spring', 'Baeldung');

这两个 SQL 文件需要放在 classpath 中,以便 Spring 能正确加载。


3. Spring 配置

要使用 MyBatis,需要引入两个核心依赖:

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.2</version>
</dependency>

同时还需要 Spring 的基础依赖:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.8</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>5.3.8</version>
</dependency>

为了简化测试,我们使用 H2 嵌入式数据库,并通过 spring-jdbc 提供的 EmbeddedDatabaseBuilder 来加载 schema 和数据:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.199</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.8</version>
</dependency>

3.1. 注解方式配置

Spring 对 MyBatis 的集成非常友好,只需配置 DataSourceSqlSessionFactory 和至少一个 Mapper 即可。

我们创建一个配置类:

@Configuration
@MapperScan("com.baeldung.mybatis")
public class PersistenceConfig {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
          .setType(EmbeddedDatabaseType.H2)
          .addScript("schema.sql")
          .addScript("data.sql")
          .build();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        return factoryBean.getObject();
    }
}

📌 使用 @MapperScan 注解可以自动扫描并注册 Mapper 接口为 Bean,无需手动注册。

接下来定义一个简单的 Mapper 接口:

public interface ArticleMapper {
    @Select("SELECT * FROM ARTICLES WHERE id = #{id}")
    Article getArticle(@Param("id") Long id);
}

最后,编写一个集成测试验证配置是否生效:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = PersistenceConfig.class)
public class ArticleMapperIntegrationTest {

    @Autowired
    ArticleMapper articleMapper;

    @Test
    public void whenRecordsInDatabase_shouldReturnArticleWithGivenId() {
        Article article = articleMapper.getArticle(1L);

        assertThat(article).isNotNull();
        assertThat(article.getId()).isEqualTo(1L);
        assertThat(article.getAuthor()).isEqualTo("Baeldung");
        assertThat(article.getTitle()).isEqualTo("Working with MyBatis in Spring");
    }
}

3.2. XML 方式配置

除了注解方式,也可以使用 XML 配置 MyBatis + Spring,主要配置包括:

<jdbc:embedded-database id="dataSource" type="H2">
    <jdbc:script location="schema.sql"/>
    <jdbc:script location="data.sql"/>
</jdbc:embedded-database>
    
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
</bean>

<bean id="articleMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="com.baeldung.mybatis.ArticleMapper" />
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

📌 注意这里使用了 spring-jdbc 提供的自定义 XML 标签来配置 H2 数据源。

测试时可以直接复用前面的测试类,只需将 @ContextConfiguration 改为:

@ContextConfiguration(locations = "classpath:/beans.xml")

4. Spring Boot 集成

Spring Boot 对 MyBatis 的集成进一步简化,只需引入一个 starter:

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

✅ 默认情况下,Spring Boot 会自动检测 classpath 中的 H2 依赖,并自动配置 DataSourceSqlSessionFactory,同时执行 schema.sqldata.sql 初始化脚本。

如果使用非嵌入式数据库,可以通过 application.ymlapplication.properties 配置连接信息,或手动定义 DataSource Bean。

📌 Mapper 接口只需加上 MyBatis 的 @Mapper 注解,Spring Boot 就会自动扫描并注册为 Bean。

测试时使用如下注解即可:

@RunWith(SpringRunner.class)
@SpringBootTest

5. 小结

本文介绍了多种在 Spring 和 Spring Boot 中集成 MyBatis 的方式:

  • 使用注解方式配置:简洁明了,适合中小型项目
  • 使用 XML 方式配置:适合传统项目或已有 XML 配置的系统
  • 使用 Spring Boot Starter:自动配置,开箱即用,推荐用于新项目

完整的示例代码已上传至 GitHub:查看完整代码

💡 小贴士:

  • ✅ Mapper 接口一定要用 @Mapper 或配置 @MapperScan
  • ✅ 数据库初始化脚本一定要放在 classpath 下
  • ✅ Spring Boot 会自动处理大部分配置,避免重复定义 Bean

如遇集成问题,建议先检查:

  • 数据源是否正确初始化
  • Mapper 接口是否被扫描到
  • SQL 脚本路径是否正确


原始标题:MyBatis with Spring