MyBatis-Spring-Boot-Starter 介紹
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.xiufeng-energy.com/archives/862.html
需要提醒的是:如果MyBatis Spring Boot Starter在Spring的上下文中至少找到一個MapperFactoryBean,那么它將不會啟動掃描過程,因此如果你想停止掃描,那么應該使用@Bean方法顯式注冊映射器。