Spring Boot 集成 Mybatis

时间:2021-06-14 19:11:19

原文:https://github.com/x113773/testall/issues/9

方式一:mybatis-spring-boot-starter
---
这种方式比较简单,具体步骤如下:
1. 首先添加依赖
```
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
```
2. application.properties添加如下配置
```
spring.datasource.url=jdbc:mysql://localhost:3306/testall?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123qwe
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis.mapper-locations=classpath:/mybatis/*.xml
mybatis.type-aliases-package=com.ansel.testall.mybatis.model
```
3. 自动扫描mapper接口(或者也可以在每个mapper接口上添加@Mapper注解)
在Application.java上添加注解@MapperScan:
```
@SpringBootApplication
@MapperScan("com.ansel.testall.mybatis.mapper")
public class Application extends SpringBootServletInitializer {
...
```
然后就可以使用mybatis-generator生成mapper接口,mapper xml,model了,关于事务详见[这里](url)。

---
方式一解释:
其实mybatis-spring-boot-starter替我们做了大部分配置:(摘自[官方文档](http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/))

> As you may already know, to use MyBatis with Spring you need at least an SqlSessionFactory and at least one mapper interface.
> MyBatis-Spring-Boot-Starter will:
> - Autodetect an existing DataSource.
> - Will create and register an instance of a SqlSessionFactory passing that DataSource as an input using the SqlSessionFactoryBean.
> - Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactory.
> - Autoscan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans.

大概翻译一下:
也许你早就知道,为了在spring上使用mybatis你至少需要一个SqlSessionFactory和一个mapper接口。
MyBatis-Spring-Boot-Starter会:
- 自动检测一个现有的DataSource(数据源)
- 通过把DataSource传送给SqlSessionFactoryBean,创建并注册一个SqlSessionFactory实例
- 使用 SqlSessionFactory 作为构造方法的参数来创建一个SqlSessionTemplate 实例
- 自动扫描mapper接口,与SqlSessionTemplate 连接,并它们注册到Spring上下文使它们可以注入到其他beans中。

如果使用方式二的话,就需要显示做出部分配置。

方式二:mybatis-spring
---
这种方式与传统的spring集成mybatis基本一致(下面展示完整的java配置版,部分xml版)

1. 还是首先添加依赖
```
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
```

2. application.properties添加如下配置
```
spring.datasource.url=jdbc:mysql://localhost:3306/testall?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123qwe
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```

3. 添加一个Mybatis的配置类MyBatisConfig.java,里面做的显示配置,基本与方式一中的自动配置一致:
```
package com.ansel.testall.mybatis;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
public class MyBatisConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}

@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {

SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
sqlSessionFactoryBean.setTypeAliasesPackage("com.ansel.testall.mybatis.model");

return sqlSessionFactoryBean.getObject();
}

@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}

/**
* 因为添加了spring-boot-starter-
* jdbc依赖,会触发DataSourceTransactionManagerAutoConfiguration这个自动化配置类
* ,自动构造事务管理器,所以若只有一个数据源可以不必进行下面的配置
*
* @return
*/
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}

```

4. 添加一个MyBatisMapperScannerConfig.java类,把mapper扫描单独放在这里配置(或者使用方法一第3步中的注解方式也可以)

```
package com.ansel.testall.mybatis;

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
// 由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解,而这个注解只能放在类上,所以...
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//因为只有一个sqlSessionFactory,所以下面这个可以不用设置
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.ansel.testall.mybatis.mapper");
return mapperScannerConfigurer;
}

}

```
---
部分xml版配置:
```
<!-- mapper自动扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ansel.testall.mybatis.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
```
```
<!-- 另外一种mapper自动扫描 -->
<mybatis:scan base-package="com.ansel.testall.mybatis.mapper" />
```