1、MyBatis-Spring-Boot-Starter 简介

MyBatis-Spring-Boot-Starter类似一个中间件,链接Spring Boot和MyBatis,构建基于Spring Boot的MyBatis应用程序。

MyBatis-Spring-Boot-Starter 当前版本是 2.1.2,发布于2020年3月10日

MyBatis-Spring-Boot-Starter是个集成包,因此对MyBatis、MyBatis-Spring和SpringBoot的jar包都存在依赖,如下所示:

MyBatis-Spring-Boot-Starter MyBatis-Spring Spring Boot Java
2.1 2.0 (need 2.0.2+ for enable all features) 2.1 or higher 8 or higher
1.3 1.3 1.5 6 or higher

2、MyBatis-Spring-Boot-Starter 安装

2.1、Maven 安装如下:

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

2.2、Gradle 安装如下:

dependencies {
  compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.1")
}

3、MyBatis-Spring-Boot-Starter 快速上手

众所周知,MyBatis的核心有两大组件:SqlSessionFactory 和 Mapper 接口。前者表示数据库链接,后者表示SQL映射。当我们基于Spring使用MyBatis的时候,也要保证在Spring环境中能存在着两大组件。

MyBatis-Spring-Boot-Starter 将会完成以下功能:

1、Autodetect an existing DataSource
自动发现存在的DataSource

2、Will create and register an instance of a SqlSessionFactory passing that DataSource as an input using the SqlSessionFactoryBean
利用SqlSessionFactoryBean创建并注册SqlSessionFactory

3、Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactory
创建并注册SqlSessionTemplate

4、Auto-scan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans
自动扫描Mappers,并注册到Spring上下文环境方便程序的注入使用

假设,我们有如下Mapper:

@Mapper
public interface CityMapper {

  @Select("SELECT * FROM CITY WHERE state = #{state}")
  City findByState(@Param("state") String state);

}

你仅仅需要创建一个Spring Boot程序让Mapper注入即可:

@SpringBootApplication
public class SampleMybatisApplication implements CommandLineRunner {

  private final CityMapper cityMapper;

  public SampleMybatisApplication(CityMapper cityMapper) {
    this.cityMapper = cityMapper;
  }

  public static void main(String[] args) {
    SpringApplication.run(SampleMybatisApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {
    System.out.println(this.cityMapper.findByState("CA"));
  }

}

仅此而已,如上程序就是一个Spring Boot程序。

4、高级扫描

默认情况下,MyBatis-Spring-Boot-Starter会查找以@Mapper注解标记的映射器。

你需要给每个MyBatis映射器标识上@Mapper注解,但是这样非常的麻烦,这时可以使用@MapperScan注解来扫描包。

备注:关于@MapperScan注解更多的介绍,请移步这里:http://www.mybatis.cn/archives/862.html

需要提醒的是:如果MyBatis Spring Boot Starter在Spring的上下文中至少找到一个MapperFactoryBean,那么它将不会启动扫描过程,因此如果你想停止扫描,那么应该使用@Bean方法显式注册映射器。

标签: none

[2024年]-[红黑树技术联盟介绍]-[成员故事]


[2024年]-[JavaOffer]-[训练营]


添加新评论