Spring Boot 中如何集成 MyBatis?

· 约 5 分钟读完 · 第 107 / 130 章

推荐答案

在 Spring Boot 中集成 MyBatis 可以通过以下步骤实现:

  1. 添加依赖:在 pom.xml 文件中添加 MyBatis 和 MyBatis-Spring-Boot-Starter 依赖。

  2. 配置数据源:在 application.properties 或 application.yml 文件中配置数据源。

  3. 创建实体类和 Mapper 接口:定义实体类和对应的 Mapper 接口。

  4. 启用 MyBatis 自动配置:在 Spring Boot 主类上添加 @MapperScan 注解,扫描 Mapper 接口。

  5. 使用 Mapper:在 Service 或 Controller 中注入 Mapper 接口并使用。

本题详细解读

1. 添加依赖

MyBatis-Spring-Boot-Starter 是 MyBatis 官方提供的 Spring Boot 集成依赖,它简化了 MyBatis 在 Spring Boot 中的配置。通过添加这个依赖,Spring Boot 会自动配置 MyBatis 所需的基本组件,如 SqlSessionFactory 和 SqlSessionTemplate。

2. 配置数据源

Spring Boot 支持多种数据源的配置,常见的有 MySQL、PostgreSQL、H2 等。在 application.properties 或 application.yml 文件中配置数据源信息后,Spring Boot 会自动创建 DataSource 实例,并将其注入到 MyBatis 中。

3. 创建实体类和 Mapper 接口

实体类通常对应数据库中的表结构,而 Mapper 接口则定义了与数据库交互的方法。通过 @Mapper 注解标记接口,MyBatis 会自动生成该接口的实现类。在 Mapper 接口中,可以使用 @Select、@Insert、@Update、@Delete 等注解来定义 SQL 语句。

4. 启用 MyBatis 自动配置

@MapperScan 注解用于指定 MyBatis Mapper 接口所在的包路径。Spring Boot 会自动扫描该路径下的所有 Mapper 接口,并将其注册为 Spring Bean。这样,在 Service 或 Controller 中就可以直接注入 Mapper 接口并使用。

5. 使用 Mapper

在 Service 或 Controller 中,通过 @Autowired 注解注入 Mapper 接口后,可以直接调用接口中定义的方法来操作数据库。这种方式使得代码更加简洁,且易于维护。

通过以上步骤,Spring Boot 与 MyBatis 的集成变得非常简单,开发者可以专注于业务逻辑的实现,而无需过多关注底层的配置细节。