MyBatis-Spring-Boot-Starter学习

本文介绍了如何在Spring Boot项目中集成MyBatis,包括Maven和Gradle的依赖管理,核心组件的自动配置,以及YAML/properties中的配置选项。重点讲解了自动扫描Mapper接口、SqlSessionFactory的创建和注册,以及自定义配置和SqlSessionFactoryBeanCustomizer的使用。

依赖安装

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")
}

大致功能

众所周知,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上下文环境方便程序的注入使用

1

MyBatis-Spring-Boot-Starter会自动找到被@Mapper注解的接口。使用@MapperScan可以指定Mapper接口的位置,免去每个接口都要@Mapper

可以获取sqlSession,具体为SqlSessionTemplate的一个实例。

@Component
public class CityDao {

  private final SqlSession sqlSession;

  public CityDao(SqlSession sqlSession) {
    this.sqlSession = sqlSession;
  }

  public City selectCityById(long id) {
    return this.sqlSession.selectOne("selectCityById", id);
  }

}

配置

如果你熟悉xml配置文件的话,都能看懂的。
yml或properties中的可选配置,以mybatis开头

Property	Description
config-location	 xml配置文件的位置
check-config-location	Indicates whether perform presence check of the MyBatis xml config file.
mapper-locations	xml映射器的位置
type-aliases-package	Packages to search for type aliases. (Package delimiters are “,; 	
”)
type-aliases-super-type	The super class for filtering type alias. If this not specifies, the MyBatis deal as type alias all classes that searched from type-aliases-package.
type-handlers-package	Packages to search for type handlers. (Package delimiters are “,; 	
”)
executor-type	Executor type: SIMPLE, REUSE, BATCH
default-scripting-language-driver	The default scripting language driver class. This feature requires to use together with mybatis-spring 2.0.2+.
configuration-properties	Externalized properties for MyBatis configuration. Specified properties can be used as placeholder on MyBatis config file and Mapper file. For detail see the MyBatis reference page.
lazy-initialization	Whether enable lazy initialization of mapper bean. Set true to enable lazy initialization. This feature requires to use together with mybatis-spring 2.0.2+.
mapper-default-scope	Default scope for mapper bean that scanned by auto-configure. This feature requires to use together with mybatis-spring 2.0.6+.
mybatis.inject-sql-session-on-mapper-scan	Set whether inject a SqlSessionTemplate or SqlSessionFactory bean (If you want to back to the behavior of 2.2.1 or before, specify false). If you use together with spring-native, should be set true(default).
configuration.*	Property keys for Configuration bean provided by MyBatis Core. About available nested properties see the MyBatis reference page. NOTE: This property cannot be used at the same time with the config-location.
scripting-language-driver.thymeleaf.*	Property keys for ThymeleafLanguageDriverConfig bean provided by MyBatis Thymeleaf. About available nested properties see the MyBatis Thymeleaf reference page.
scripting-language-driver.freemarker.*	Properties keys for FreeMarkerLanguageDriverConfig bean provided by MyBatis FreeMarker. About available nested properties see the MyBatis FreeMarker reference page. This feature requires to use together with mybatis-freemarker 1.2.0+.
scripting-language-driver.velocity.*	Properties keys for VelocityLanguageDriverConfig bean provided by MyBatis Velocity. About available nested properties see the MyBatis Velocity reference page. This feature requires to use together with mybatis-velocity 2.1.0+.

ConfigurationCustomizer

MyBatis-Spring-Boot-Starter 提供了自定义 MyBatis 配置的机会,该配置由使用 Java Config 自动配置生成。 MyBatis-Spring-Boot-Starter 会自动搜索实现 ConfigurationCustomizer 接口的 bean,并调用customize方法。 (自 1.2.1 或更高版本可用

@Configuration
public class MyBatisConfig {
  @Bean
  ConfigurationCustomizer mybatisConfigurationCustomizer() {
    return new ConfigurationCustomizer() {
      @Override
      public void customize(Configuration configuration) {
        // customize ...
      }
    };
  }
}

SqlSessionFactoryBeanCustomizer

对于SqlSessionFactoryBean,MyBatis-Spring-Boot-Starter 提供了使用 Java Config 自定义自动配置生成的机会。MyBatis-Spring-Boot-Starter 会自动搜索实现了SqlSessionFactoryBeanCustomizer接口的 bean,并调用其customize方法。 (自 2.2.2 或更高版本可用)

@Configuration
public class MyBatisConfig {
  @Bean
  SqlSessionFactoryBeanCustomizer sqlSessionFactoryBeanCustomizer() {
    return new SqlSessionFactoryBeanCustomizer() {
      @Override
      public void customize(SqlSessionFactoryBean factoryBean) {
        // customize ...
      }
    };
  }
}

SpringBootVFS

当使用多个数据源时

@Configuration
public class MyBatisConfig {
  @Bean
  public SqlSessionFactory masterSqlSessionFactory() throws Exception {
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    factoryBean.setDataSource(masterDataSource());
    factoryBean.setVfs(SpringBootVFS.class); // Sets the SpringBootVFS class into SqlSessionFactoryBean
    // ...
    return factoryBean.getObject();
  }
}

检测 MyBatis 组件

MyBatis-Spring-Boot-Starter 将检测实现 MyBatis 提供的以下接口的 bean。

Interceptor
TypeHandler
LanguageDriver(需要配合mybatis-spring 2.0.2+使用)
DatabaseIdProvider

@Configuration
public class MyBatisConfig {
  @Bean
  MyInterceptor myInterceptor() {
    return MyInterceptor();
  }
  @Bean
  MyTypeHandler myTypeHandler() {
    return MyTypeHandler();
  }
  @Bean
  MyLanguageDriver myLanguageDriver() {
    return MyLanguageDriver();
  }
  @Bean
  VendorDatabaseIdProvider databaseIdProvider() {
    VendorDatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
    Properties properties = new Properties();
    properties.put("SQL Server", "sqlserver");
    properties.put("DB2", "db2");
    properties.put("H2", "h2");
    databaseIdProvider.setProperties(properties);
    return databaseIdProvider;
  }  
}

LanguageDriver 的自定义

如果您想自定义LanguageDriver通过自动配置创建的,请注册用户定义的 bean。

ThymeleafLanguageDriver

@Configuration
public class MyBatisConfig {
  @Bean
  ThymeleafLanguageDriverConfig thymeleafLanguageDriverConfig() {
    return ThymeleafLanguageDriverConfig.newInstance(c -> {
      // ... customization code
    });
  }
}
当遇到 mybatis-spring-boot-starter 无法找到的问题,可从以下几个方面着手解决: 1. **依赖检查**:mybatis-plus-boot-starter 内部已包含 mybatis-spring-boot-starter 的依赖或者关键依赖,若项目中同时引入这两个 starter,移除其中一个通常不会影响项目运行。所以要检查项目依赖,避免重复引入导致冲突。若已引入 mybatis-plus-boot-starter,可考虑移除 mybatis-spring-boot-starter 单独的依赖配置,反之亦然 [^1]。 2. **依赖配置检查**:确保在项目的构建文件(如 Maven 的 `pom.xml` 或 Gradle 的 `build.gradle`)中正确配置了 mybatis-spring-boot-starter 依赖。 - **Maven 示例**: ```xml <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>合适的版本号</version> </dependency> ``` - **Gradle 示例**: ```groovy implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:合适的版本号' ``` 3. **版本兼容性**:检查所使用的 mybatis-spring-boot-starter 版本是否与项目中的其他依赖(如 Spring Boot 版本)兼容。不兼容的版本可能导致依赖无法正确解析。 4. **仓库配置**:确保项目的构建工具(Maven 或 Gradle)配置了正确的仓库地址,以便能够从中央仓库或其他指定仓库下载依赖。 5. **缓存清理**:清理构建工具的本地缓存,Maven 可删除 `~/.m2/repository` 目录下相关依赖,Gradle 可删除 `~/.gradle/caches` 目录下的缓存,然后重新构建项目。 6. **Mapper 文件配置**:MyBatis-Spring-Boot-Starter 默认会寻找标注有 `@Mapper` 的 mapper 文件,若一个个配置较繁琐,可使用 `@MapperScan` 标注法进行统一配置。可参考 mybatis-spring-boot-starter 模块文档:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/index.html [^2][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值