MyBatis-Spring-Boot-Starter学习

贾成天
2023-12-01

依赖安装

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 “,; \t\n”)
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 “,; \t\n”)
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
    });
  }
}
 类似资料: