spring-boot-starter Documentation

MyBatis integration with Spring Boot

4,248 stars Java Java 1 file · ~17,262 tokens #java#mybatis#spring-boot
RAW Doc

File: README.md

MyBatis integration with Spring Boot





MyBatis Spring-Boot-Starter will help you to use MyBatis with Spring Boot

Requirements

  • master : MyBatis 3.5, MyBatis-Spring 4.1, Java 17+ and Spring Boot 4.1
  • 4.0.x : MyBatis 3.5, MyBatis-Spring 4.0, Java 17+ and Spring Boot 4.0
  • 3.0.x : MyBatis 3.5, MyBatis-Spring 3.0, Java 17+ and Spring Boot 3.2-3.5
  • 2.3.x : MyBatis 3.5, MyBatis-Spring 2.1, Java 8+ and Spring Boot 2.7

Compatibility Check

  • Compatibility with Spring Boot 2.7 - 4.0 here

Creating new project via Spring Initializr

Essentials

Published documentations

Snapshot documentations

Translations:

Quick Start

Quick Start for building native image

Bug report & Feature request

Question


File: renovate.json

{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:recommended",
"helpers:pinGitHubActionDigests"
]
}


File: mybatis-spring-boot-autoconfigure/src/main/resources/META-INF/additional-spring-configuration-metadata.json

{
"properties": [
{
"defaultValue": false,
"name": "mybatis.lazy-initialization",
"description": "Set whether enable lazy initialization for mapper bean.",
"type": "java.lang.Boolean"
},
{
"defaultValue": "",
"name": "mybatis.mapper-default-scope",
"description": "A default scope for mapper bean that scanned by auto-configure.",
"type": "java.lang.String"
},
{
"defaultValue": true,
"name": "mybatis.inject-sql-session-on-mapper-scan",
"description": "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.",
"type": "java.lang.Boolean"
},
{
"name": "mybatis.scripting-language-driver.velocity.userdirective",
"deprecation": {
"level": "error",
"reason": "The 'userdirective' is deprecated since Velocity 2.x. This property defined for keeping backward compatibility with older velocity version.",
"replacement": "mybatis.scripting-language-driver.velocity.velocity-settings.runtime.custom_directives"
}
}
]
}


File: mybatis-spring-boot-autoconfigure/src/site/markdown/index.md

Introduction

Translations

Users can read about MyBatis-Spring-Boot-Starter in the following translations:

  • [English](./index.html)
  • [简体中文](./zh_CN/index.html)
  • What is MyBatis-Spring-Boot-Starter?

    The MyBatis-Spring-Boot-Starter help you build quickly MyBatis applications on top of the Spring Boot.

    By using this module you will achieve:

    • Build standalone applications
    • Reduce the boilerplate to almost zero
    • Less XML configuration

    Requirements

    The MyBatis-Spring-Boot-Starter requires following versions:

    MyBatis-Spring-Boot-Starter MyBatis-Spring Spring Boot Java
    4.0 4.0 4.0+ 17 or higher
    3.0 3.0 3.2 - 3.5 17 or higher
    2.3 2.1 2.7 8 or higher
    2.2 (EOL) 2.0 (need 2.0.6+ for enable all features) 2.5 - 2.7 8 or higher
    2.1 (EOL) 2.0 (need 2.0.6+ for enable all features) 2.1 - 2.4 8 or higher
    2.0 (EOL) 2.0 2.0 or 2.1 8 or higher
    1.3 (EOL) 1.3 1.5 6 or higher
    1.2 (EOL) 1.3 1.4 6 or higher
    1.1 (EOL) 1.3 1.3 6 or higher
    1.0 (EOL) 1.2 1.3 6 or higher

    Installation

    To use the MyBatis-Spring-Boot-Starter module, you just need to include the mybatis-spring-boot-autoconfigure.jar file and its dependencies(mybatis.jar, mybatis-spring.jar and etc ...) in the classpath.

    Maven

    If you are using Maven just add the following dependency to your pom.xml:

    xml
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>${project.version}</version>
    </dependency>

    Gradle

    If using gradle add this to your build.gradle:

    groovy
    dependencies {
      implementation("org.mybatis.spring.boot:mybatis-spring-boot-starter:${project.version}")
    }

    Quick Setup

    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
    • Auto-scan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans

    Suppose we have the following mapper:

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

    You just need to create a normal Spring boot application and let the mapper be injected like follows(available on Spring 4.3+):

    java
    @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"));
      }
    
    }

    This is all you have to do. You application can now be run as a normal Spring Boot application.

    Advanced scanning

    The MyBatis-Spring-Boot-Starter will search, by default, for mappers marked with the @Mapper annotation.

    You may want to specify a custom annotation or a marker interface for scanning. If so, you must use the @MapperScan annotation. See more about it in the MyBatis-Spring reference page.

    The MyBatis-Spring-Boot-Starter will not start the scanning process if it finds at least one MapperFactoryBean in the Spring's context so if you want to stop the scanning at all you should register your mappers explicitly with @Bean methods.

    Using an SqlSession

    An instance of a SqlSessionTemplate is created and added to the Spring context, so you can use the MyBatis API letting it be injected into your beans like follows(available on Spring 4.3+):

    java
    @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);
      }
    
    }

    Configuration

    As any other Spring Boot application a MyBatis-Spring-Boot-Application configuration parameters are stored inside the application.properties(or application.yml).

    MyBatis uses the prefix mybatis for its properties.

    Available properties are:

    Property Description
    config-location Location of MyBatis xml config file.
    check-config-location Indicates whether perform presence check of the MyBatis xml config file.
    mapper-locations Locations of Mapper xml config file.
    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+.
    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+.

    For example:

    properties
    # application.properties
    mybatis.type-aliases-package=com.example.domain.model
    mybatis.type-handlers-package=com.example.typehandler
    mybatis.configuration.map-underscore-to-camel-case=true
    mybatis.configuration.default-fetch-size=100
    mybatis.configuration.default-statement-timeout=30
    ...
    yaml
    # application.yml
    mybatis:
        type-aliases-package: com.example.domain.model
        type-handlers-package: com.example.typehandler
        configuration:
            map-underscore-to-camel-case: true
            default-fetch-size: 100
            default-statement-timeout: 30
    ...

    Using a ConfigurationCustomizer

    The MyBatis-Spring-Boot-Starter provide opportunity to customize a MyBatis configuration generated by auto-configuration using Java Config.
    The MyBatis-Spring-Boot-Starter will search beans that implement the ConfigurationCustomizer interface by automatically,
    and call a method that customize a MyBatis configuration. (Available since 1.2.1 or above)

    For example:

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

    Using a SqlSessionFactoryBeanCustomizer

    The MyBatis-Spring-Boot-Starter provide opportunity to customize a SqlSessionFactoryBean generated by auto-configuration using Java Config.
    The MyBatis-Spring-Boot-Starter will search beans that implement the SqlSessionFactoryBeanCustomizer interface by automatically,
    and call a method that customize a SqlSessionFactoryBean. (Available since 2.2.2 or above)

    For example:

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

    Using the SpringBootVFS

    The MyBatis-Spring-Boot-Starter provides the SpringBootVFS as an implementation class of VFS.
    The VFS is used for searching classes (e.g. target class of type alias, type handler class) from an application (or application server).
    If you run a Spring Boot application using the executable jar, you need to use the SpringBootVFS.
    The auto-configuration feature provided by the MyBatis-Spring-Boot-Starter used it automatically,
    but it does not use automatically by a manual configuration (e.g. when uses multiple DataSource).

    How to use the SpringBootVFS on manual configuration:

    java
    @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();
      }
    }

    Detecting MyBatis components

    The MyBatis-Spring-Boot-Starter will detects beans that implements following interface provided by MyBatis.

    java
    @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;
      }
    }

    NOTE: If detected LangaugeDriver's count is one, it set to default scripting language automatically.

    Customization for LanguageDriver

    If you want to customize the LanguageDriver that creating by auto-configure,
    please register user defined bean.

    ThymeleafLanguageDriver

    java
    @Configuration
    public class MyBatisConfig {
      @Bean
      ThymeleafLanguageDriverConfig thymeleafLanguageDriverConfig() {
        return ThymeleafLanguageDriverConfig.newInstance(c -> {
          // ... customization code
        });
      }
    }

    FreeMarkerLanguageDriverConfig

    java
    @Configuration
    public class MyBatisConfig {
      @Bean
      FreeMarkerLanguageDriverConfig freeMarkerLanguageDriverConfig() {
        return FreeMarkerLanguageDriverConfig.newInstance(c -> {
          // ... customization code
        });
      }
    }

    VelocityLanguageDriver

    java
    @Configuration
    public class MyBatisConfig {
      @Bean
      VelocityLanguageDriverConfig velocityLanguageDriverConfig() {
        return VelocityLanguageDriverConfig.newInstance(c -> {
          // ... customization code
        });
      }
    }

    Running Samples

    The project provides two samples so you play and experiment with them:

    Category Sample Description
    Core 1st Sample Show the simplest scenario with just a mapper and a bean where the mapper is injected into. This is the sample we saw in the Quick Setup section.
    2nd Sample Shows how to use a Mapper that has its statements in an xml file and Dao that uses an SqlSessionTemplate.
    LanguageDriver 3rd Sample Shows how to use the language driver for Thymeleaf with mybatis-thymeleaf.
    4th Sample Shows how to use the language driver for FreeMarker with mybatis-freemarker.
    5th Sample Shows how to use the language driver for Velocity with mybatis-velocity.
    JVM Language 6th Sample Shows how to use with kotlin.
    7th Sample Shows how to use with groovy.
    Web 8th Sample Show how to use the web environment.
    9th Sample Show how to use the web environment with war(=deploy to the application server).

    File: mybatis-spring-boot-autoconfigure/src/site/zh_CN/markdown/index.md

    简介

    文档的翻译版本

    可以阅读 MyBatis-Spring-Boot-Starter 文档的以下翻译版本:

  • [English](./../index.html)
  • [简体中文](./../zh_CN/index.html)
  • 什么是 MyBatis-Spring-Boot-Starter?

    MyBatis-Spring-Boot-Starter 可以帮助你更快地在 Spring Boot 之上构建 MyBatis 应用。

    你将通过使用这个模块实现以下目的:

    • 构建单体应用程序
    • 将几乎不需要样板配置
    • 使用更少的 XML 配置

    要求

    MyBatis-Spring-Boot-Starter 要求以下版本:

    MyBatis-Spring-Boot-Starter MyBatis-Spring Spring Boot Java
    4.0 4.0 4.0+ 17 或更高
    3.0 3.0 3.2 - 3.5 17 或更高
    2.3 2.1 2.7 8 或更高
    2.2 (EOL) 2.0(2.0.6 以上可开启所有特性) 2.5 - 2.7 8 或更高
    2.1 (EOL) 2.0(2.0.6 以上可开启所有特性) 2.1 - 2.4 8 或更高
    2.0 (EOL) 2.0 2.0 或 2.1 8 或更高
    1.3 (EOL) 1.3 1.5 6 或更高
    1.2 (EOL) 1.3 1.4 6 或更高
    1.1 (EOL) 1.3 1.3 6 或更高
    1.0 (EOL) 1.2 1.3 6 或更高

    安装

    要使用 MyBatis-Spring-Boot-Starter 模块,你只需要将 mybatis-spring-boot-autoconfigure.jar 文件以及它的依赖( mybatis.jar, mybatis-spring.jar 等) 放在类路径下。

    Maven

    如果你使用 Maven,只需要在你的 pom.xml 添加以下依赖:

    xml
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>${project.version}</version>
    </dependency>

    Gradle

    如果使用 gradle,请在你的 build.gradle 中加入以下内容:

    groovy
    dependencies {
      implementation("org.mybatis.spring.boot:mybatis-spring-boot-starter:${project.version}")
    }

    快速开始

    正如你已经知道的, 要与 Spring 一起使用 MyBatis,你至少需要一个 SqlSessionFactory 和一个 mapper 接口。

    MyBatis-Spring-Boot-Starter 将会:

    • 自动探测存在的 DataSource
    • 将使用 SqlSessionFactoryBean 创建并注册一个 SqlSessionFactory 的实例,并将探测到的 DataSource 作为数据源
    • 将创建并注册一个从 SqlSessionFactory 中得到的 SqlSessionTemplate 的实例
    • 自动扫描你的 mapper,将它们与 SqlSessionTemplate 相关联,并将它们注册到Spring 的环境(context)中去,这样它们就可以被注入到你的 bean 中

    假设我们有下面的 mapper :

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

    你只需要创建一个 Spring boot 应用,像下面这样,将 mapper 注入进去( Spring 4.3 以上可用)。

    java
    @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 应用可以正常运行了。

    “扫描”的进阶用法

    MyBatis-Spring-Boot-Starter 将默认搜寻带有 @Mapper 注解的 mapper 接口。

    你可能想指定一个自定义的注解或接口来扫描,如果那样的话,你就必须使用 @MapperScan 注解了。在 MyBatis-Spring 参考页面 中查看更多信息。

    如果 MyBatis-Spring-Boot-Starter 发现至少有一个 SqlSessionFactoryBean ,它将不会开始扫描。 所以如果你想停止扫描,你应该用 @Bean 方法明确注册你的 mapper。

    使用 SqlSession

    一个 SqlSessionTemplate 的实例被创建并添加到 Spring 的环境中,因此你可以使用 MyBatis API,让它像下面一样被注入到你的 bean 中(Spring 4.3 以上可用)。

    java
    @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);
      }
    
    }

    配置

    像其他的 Spring Boot 应用一样,配置参数在 application.properties (或 application.yml )。

    MyBatis 在它的配置项中,使用 mybatis 作为前缀。

    可用的配置项如下:

    配置项(properties) 描述
    config-location MyBatis XML 配置文件的路径。
    check-config-location 指定是否对 MyBatis XML 配置文件的存在进行检查。
    mapper-locations XML 映射文件的路径。
    type-aliases-package 搜索类型别名的包名。(包使用的分隔符是 ",; \t\n")
    type-aliases-super-type 用于过滤类型别名的父类。如果没有指定,MyBatis会将所有从 type-aliases-package 搜索到的类作为类型别名处理。
    type-handlers-package 搜索类型处理器的包名。(包使用的分隔符是 ",; \t\n")
    executor-type SQL 执行器类型: SIMPLE, REUSE, BATCH
    default-scripting-language-driver 默认的脚本语言驱动(模板引擎),此功能需要与 mybatis-spring 2.0.2 以上版本一起使用。
    configuration-properties 可在外部配置的 MyBatis 配置项。指定的配置项可以被用作 MyBatis 配置文件和 Mapper 文件的占位符。更多细节 见 MyBatis 参考页面。
    lazy-initialization 是否启用 mapper bean 的延迟初始化。设置 true 以启用延迟初始化。此功能需要与 mybatis-spring 2.0.2 以上版本一起使用。
    mapper-default-scope 通过自动配置扫描的 mapper 组件的默认作用域。该功能需要与 mybatis-spring 2.0.6 以上版本一起使用。
    inject-sql-session-on-mapper-scan 设置是否注入 SqlSessionTemplate 或  SqlSessionFactory 组件 (如果你想回到 2.2.1 或之前的行为,请指定 false )。如果你和 spring-native 一起使用,应该设置为 true (默认)。
    configuration.* MyBatis Core 提供的Configuration 组件的配置项。有关可用的内部配置项,请参阅MyBatis 参考页面。注:此属性不能与 config-location 同时使用。
    scripting-language-driver.thymeleaf.* MyBatis ThymeleafLanguageDriverConfig 组件的 properties keys。有关可用的内部配置项,请参阅 MyBatis Thymeleaf 参考页面。
    scripting-language-driver.freemarker.* MyBatis FreemarkerLanguageDriverConfig 组件的 properties keys。有关可用的内部配置项,请参阅 MyBatis FreeMarker 参考页面。这个特性需要与 mybatis-freemarker 1.2.0 以上版本一起使用。
    scripting-language-driver.velocity.* MyBatis VelocityLanguageDriverConfig 组件的  properties keys。有关可用的内部属性,请参阅 MyBatis Velocity 参考页面。这个特性需要与 mybatis-velocity 2.1.0 以上版本一起使用。

    例如:

    properties
    # application.properties
    mybatis.type-aliases-package=com.example.domain.model
    mybatis.type-handlers-package=com.example.typehandler
    mybatis.configuration.map-underscore-to-camel-case=true
    mybatis.configuration.default-fetch-size=100
    mybatis.configuration.default-statement-timeout=30
    ...
    yaml
    # application.yml
    mybatis:
        type-aliases-package: com.example.domain.model
        type-handlers-package: com.example.typehandler
        configuration:
            map-underscore-to-camel-case: true
            default-fetch-size: 100
            default-statement-timeout: 30
    ...

    使用 ConfigurationCustomizer

    MyBatis-Spring-Boot-Starter 提供了使用 Java Config 来自定义 MyBatis 配置的可能。

    MyBatis-Spring-Boot-Starter 将自动寻找实现了 ConfigurationCustomizer 接口的组件,调用自定义 MyBatis 配置的方法。( 1.2.1 及以上的版本可用)

    例如:

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

    使用 SqlSessionFactoryBeanCustomizer

    MyBatis-Spring-Boot-Starter 提供了使用 Java Config 来自定义自动配置生成的 SqlSessionFactoryBean 。

    MyBatis-Spring-Boot-Starter 将自动寻找实现了 SqlSessionFactoryBeanCustomizer 接口的组件,调用自定义 SqlSessionFactoryBean 的方法。( 2.2.2 及以上的版本可用)

    For example:

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

    使用 SpringBootVFS

    MyBatis-Spring-Boot-Starter 提供了 SpringBootVFS 作为 VFS 的实现类。
    VFS 用于从应用或应用服务器中寻找类 (例如: 类型别名的目标类,类型处理器类) 。
    如果你使用可执行的 jar 文件来运行 Spring boot 应用,你需要使用 SpringBootVFS 。
    由于拥有自动配置的特性,MyBatis-Spring-Boot-Starter 会自动启用它。
    但在你手动配置(MyBatis-Spring-Boot-Starter)的时候 (例如: 当你使用多个 DataSource 的时候)。

    在手动配置(MyBatis-Spring-Boot-Starter)的时候,这样使用 SpringBootVFS :

    java
    @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 组件

    The MyBatis-Spring-Boot-Starter 将检测实现以下由 MyBatis 提供的接口的组件。

    java
    @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;
      }
    }

    注意: 如果只有一个 LangaugeDriver ,它将自动地将其作为默认的脚本语言。

    如果你想自定义 LangaugeDriver 的配置,请注册用户定义的组件。

    ThymeleafLanguageDriver

    java
    @Configuration
    public class MyBatisConfig {
      @Bean
      ThymeleafLanguageDriverConfig thymeleafLanguageDriverConfig() {
        return ThymeleafLanguageDriverConfig.newInstance(c -> {
          // ... 自定义代码
        });
      }
    }

    FreeMarkerLanguageDriverConfig

    java
    @Configuration
    public class MyBatisConfig {
      @Bean
      FreeMarkerLanguageDriverConfig freeMarkerLanguageDriverConfig() {
        return FreeMarkerLanguageDriverConfig.newInstance(c -> {
          // ... 自定义代码
        });
      }
    }

    VelocityLanguageDriver

    java
    @Configuration
    public class MyBatisConfig {
      @Bean
      VelocityLanguageDriverConfig velocityLanguageDriverConfig() {
        return VelocityLanguageDriverConfig.newInstance(c -> {
          // ... customization code
        });
      }
    }

    可以运行的样例

    项目(为每个分类)提供了至少两个样例,可以为你所用。

    分类 样例 描述
    核心组件 样例1 展示了最简单的场景,只有一个 mapper 和一个注入 mapper 的组件。这就是我们在“快速入门”部分看到的例子。
    样例2 展示了如何在 XML 文件中使用一个带有语句的 Mapper,并且也有使用 SqlSessionTemplate 的 DAO 的示例。
    LanguageDriver 样例3 展示了如何在 mybatis-thymeleaf 的帮助下,使用 Thymeleaf。
    样例4 展示了如何在 mybatis-freemarker 的帮助下,使用 Freemarker。
    样例5 展示了如何在 mybatis-velocity 的帮助下,使用 Velocity。
    JVM 语言 样例6 展示了如何和 kotlin 一同使用。
    样例7 展示了如何和 groovy 一同使用。
    Web 样例8 展示了如何在 web 环境中使用。
    样例9 展示了如何在 web 环境中使用并且让 war 文件部署在应用程序服务器上。

    File: mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-city.yaml

    Licensed under the Apache License, Version 2.0 (the "License");

    you may not use this file except in compliance with the License.

    You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software

    distributed under the License is distributed on an "AS IS" BASIS,

    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

    See the License for the specific language governing permissions and

    limitations under the License.

    databaseChangeLog:

    • changeSet:
      id: 1
      author: dsyer
      changes:
      - createSequence:
      sequenceName: hibernate_sequence
      - createTable:
      tableName: city
      columns:
      - column:
      name: id
      type: bigint
      autoIncrement: true
      constraints:
      primaryKey: true
      nullable: false
      - column:
      name: name
      type: varchar(50)
      constraints:
      nullable: false
      - column:
      name: state
      type: varchar(50)
      constraints:
      nullable: false
      - column:
      name: country
      type: varchar(50)
      constraints:
      nullable: false
      - column:
      name: map
      type: varchar(50)
      constraints:
      nullable: true

    File: mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-master.yaml

    Licensed under the Apache License, Version 2.0 (the "License");

    you may not use this file except in compliance with the License.

    You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software

    distributed under the License is distributed on an "AS IS" BASIS,

    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

    See the License for the specific language governing permissions and

    limitations under the License.

    databaseChangeLog:

    • changeSet:
      id: 1
      author: marceloverdijk
      changes:
      - createTable:
      tableName: customer
      columns:
      - column:
      name: id
      type: int
      autoIncrement: true
      constraints:
      primaryKey: true
      nullable: false
      - column:
      name: name
      type: varchar(50)
      constraints:
      nullable: false

    File: mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-override.json

    {
    "databaseChangeLog": [
    {
    "changeSet": {
    "author": "awilkinson",
    "id": "1",
    "changes": [
    {
    "createTable": {
    "tableName": "customer",
    "columns": [
    {
    "column": {
    "name": "id",
    "type": "int",
    "autoIncrement": true,
    "constraints": {
    "nullable": false,
    "primaryKey": true
    }
    }
    },
    {
    "column": {
    "name": "name",
    "type": "varchar(50)",
    "constraints": {
    "nullable": false
    }
    }
    }
    ]
    }
    }
    ]
    }
    }
    ]
    }


    File: mybatis-spring-boot-test-autoconfigure/src/site/markdown/index.md

    Introduction

    Translations

    Users can read about MyBatis-Spring-Boot-Starter-Test in the following translations:

  • [English](./index.html)
  • [简体中文](./zh_CN/index.html)
  • What is MyBatis-Spring-Boot-Starter-Test?

    The MyBatis-Spring-Boot-Starter-Test help creating a test cases for MyBatis component using the MyBatis-Spring-Boot-Starter.

    By using this module you will can be:

    • Can use the @MybatisTest that setup test components for testing pure MyBatis component
    • Can import dependency artifacts for performing tests for pure MyBatis component

    Requirements

    The MyBatis-Spring-Boot-Starter-Test requires following versions:

    MyBatis-Spring-Boot-Starter-Test Spring Boot Java
    4.0 4.0+ 17 or higher
    3.0 3.2 - 3.5 17 or higher
    2.3 2.7 8 or higher
    2.2 (EOL) 2.5 - 2.7 8 or higher
    2.1 (EOL) 2.1 - 2.4 8 or higher
    2.0 (EOL) 2.0 or 2.1 8 or higher
    1.3 (EOL) 1.5 6 or higher
    1.2 (EOL) 1.4 6 or higher

    Installation

    Maven

    If you are using Maven just add the following dependency to your pom.xml:

    xml
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter-test</artifactId>
        <version>${project.version}</version>
        <scope>test</scope>
    </dependency>

    Gradle

    If using gradle add this to your build.gradle:

    groovy
    dependencies {
        testImplementation("org.mybatis.spring.boot:mybatis-spring-boot-starter-test:${project.version}")
    }

    Using @MybatisTest

    The @MybatisTest can be used if you want to test MyBatis components(Mapper interface and SqlSession).
    By default it will configure MyBatis(MyBatis-Spring) components(SqlSessionFactory and SqlSessionTemplate),
    configure MyBatis mapper interfaces and configure an in-memory embedded database.
    MyBatis tests are transactional and rollback at the end of each test by default,
    for more details refer to the relevant section in the Spring Reference Documentation.
    Also regular @Component beans will not be loaded into the ApplicationContext.

    Test for Mapper interface

    if you create a test case for following mapper interface, you add just @MybatisTest on your test case class.

    Mapper interface :

    java
    package sample.mybatis.mapper;
    
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    import sample.mybatis.domain.City;
    
    @Mapper
    public interface CityMapper {
    
        @Select("SELECT * FROM CITY WHERE state = #{state}")
        City findByState(@Param("state") String state);
    
    }

    TestCase class :

    java
    package sample.mybatis.mapper;
    
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.mybatis.spring.boot.test.autoconfigure.MybatisTest;
    import sample.mybatis.domain.City;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import static org.assertj.core.api.Assertions.assertThat;
    
    @RunWith(SpringRunner.class)
    @MybatisTest
    public class CityMapperTest {
    
        @Autowired
        private CityMapper cityMapper;
    
        @Test
        public void findByStateTest() {
            City city = cityMapper.findByState("CA");
            assertThat(city.getName()).isEqualTo("San Francisco");
            assertThat(city.getState()).isEqualTo("CA");
            assertThat(city.getCountry()).isEqualTo("US");
        }
    
    }

    Test for DAO pattern

    if you create a test case for following DAO class, you add just @MybatisTest and @Import on your test case class.

    DAO class :

    java
    package sample.mybatis.dao;
    
    import org.apache.ibatis.session.SqlSession;
    import sample.mybatis.domain.City;
    
    import org.springframework.stereotype.Component;
    
    @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);
        }
    
    }

    TestCase class :

    java
    package sample.mybatis.dao;
    
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.mybatis.spring.boot.test.autoconfigure.MybatisTest;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Import;
    import org.springframework.test.context.junit4.SpringRunner;
    import sample.mybatis.domain.City;
    
    import static org.assertj.core.api.Assertions.assertThat;
    
    @RunWith(SpringRunner.class)
    @MybatisTest
    @Import(CityDao.class)
    public class CityDaoTest {
    
        @Autowired
        private CityDao cityDao;
    
        @Test
        public void selectCityByIdTest() {
            City city = cityDao.selectCityById(1);
            assertThat(city.getName()).isEqualTo("San Francisco");
            assertThat(city.getState()).isEqualTo("CA");
            assertThat(city.getCountry()).isEqualTo("US");
        }
    
    }

    Using a real database

    The In-memory embedded databases generally work well for tests since they are fast and don’t require any developer installation.
    However if you prefer to run tests against a real database, you can use the @AutoConfigureTestDatabase as follow:

    java
    package sample.mybatis.mapper;
    // ...
    import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
    
    @RunWith(SpringRunner.class)
    @MybatisTest
    @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
    public class CityMapperTest {
        // ...
    }

    Prevent detecting a real @SpringBootApplication

    The @MybatisTest will detect a class that annotated @SpringBootApplication by default.
    Therefore by depend on bean definition methods, there is case that an unexpected error is occurred or unnecessary components are loaded into ApplicationContext.
    This behavior can prevent by creating a @SpringBootApplication class into same package as test class as follow:

    java
    package sample.mybatis.mapper;
    
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    class MapperTestApplication {
    
    }

    Use together with other @***Test

    If you use the @MybatisTest together with other @***Test(e.g. @WebMvcTest),
    Please consider to use the @AutoConfigureMybatis because @***Test annotation cannot specify two or more on same test.

    Target classes for testing:

    java
    @RestController
    public class PingController {
      PingMapper mapper;
    
      PingController(PingMapper mapper) {
        this.mapper = mapper;
      }
    
      @GetMapping("ping")
      String ping() {
        return mapper.ping();
      }
    }
    java
    @Mapper
    public interface PingMapper {
    @Select("SELECT 'OK'")
      String ping();
    }

    Test class:

    java
    @RunWith(SpringRunner.class)
    @WebMvcTest
    @AutoConfigureMybatis // Specify instead of @MybatisTest
    public class PingTests {
    
      @Autowired
      private MockMvc mvc;
    
      @Test
      public void ping() throws Exception {
        this.mvc.perform(get("/ping"))
            .andExpect(status().isOk())
            .andExpect(content().string("OK"));
      }
    
    }

    Using @MybatisTest on JUnit 5

    The @MybatisTest can be used on JUnit 5.

    java
    @ExtendWith(SpringExtension.class)
    @MybatisTest
    public class CityMapperTest {
        // ...
    }

    Since 2.0.1, the @ExtendWith(SpringExtension.class) can omit as follow:

    java
    @MybatisTest
    public class CityMapperTest {
        // ...
    }

    Appendix

    Imported auto-configuration

    The @MybatisTest will import following auto-configuration classes.

    • org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
    • org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration
    • org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
    • org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
    • org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration
    • org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration
    • org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration
    • org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration
    • org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration
    • org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

    Running Samples

    The project provides two samples so you play and experiment with them.

    Category Sample Description
    Core 1st Sample Show the simplest scenario with just a mapper and a bean where the mapper is injected into. This is the sample we saw in the Quick Setup section.
    2nd Sample Shows how to use a Mapper that has its statements in an xml file and Dao that uses an SqlSessionTemplate.
    JVM Language 3rd Sample Shows how to use with kotlin.
    4th Sample Shows how to use with groovy.

    File: mybatis-spring-boot-test-autoconfigure/src/site/zh_CN/markdown/index.md

    简介

    文档的翻译版本

    可以阅读 MyBatis-Spring-Boot-Starter-Test 文档的以下翻译版本:

  • [English](./../index.html)
  • [简体中文](./../zh_CN/index.html)
  • 什么是 MyBatis-Spring-Boot-Starter-Test?

    MyBatis-Spring-Boot-Starter-Test 为 MyBatis-Spring-Boot-Starter 中的 MyBatis 组件提供测试用例。

    使用它你将可以做到:

    • 可以使用 @MybatisTest 单独为 MyBatis 组件进行测试
    • 在测试 MyBatis 组件时,可以导入依赖

    TheMyBatis-Spring-Boot-Starter-Test 要求以下版本:

    MyBatis-Spring-Boot-Starter-Test Spring Boot Java
    4.0 4.0+ 17 或更高
    3.0 3.2 - 3.5 17 或更高
    2.3 2.7 8 或更高
    2.2 (EOL) 2.5 - 2.7 8 或更高
    2.1 (EOL) 2.1 - 2.4 8 或更高
    2.0 (EOL) 2.0 或 2.1 8 或更高
    1.3 (EOL) 1.5 6 或更高
    1.2 (EOL) 1.4 6 或更高

    安装

    Maven

    如果你使用 Maven,只需要将下面的依赖放入你的 pom.xml:

    xml
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter-test</artifactId>
        <version>${project.version}</version>
        <scope>test</scope>
    </dependency>

    Gradle

    如果使用 Gradle,在 build.gradle 中加入以下内容:

    groovy
    dependencies {
        testImplementation("org.mybatis.spring.boot:mybatis-spring-boot-starter-test:${project.version}")
    }

    使用 @MybatisTest

    当你想对 MyBatis 组件进行测试时,可以使用 @MybatisTest (Mapper 接口与 SqlSession)。
    默认情况下, 它将会配置 MyBatis(MyBatis-Spring)组件(SqlSessionFactory 与 SqlSessionTemplate),配置 MyBatis mapper 接口和内存中的内嵌的数据库。
    MyBatis 测试默认情况下基于事务,且在测试的结尾进行回滚。
    更多相关的信息可参见 Spring 参考文档 。
    再者,普遍情况下 @Component beans 将不会被载入 ApplicationContext 。

    对 Mapper 接口进行测试

    如果你想对下面的 Mapper 接口进行测试,你只需要将 @MybatisTest 添加在测试类上。

    Mapper 接口:

    java
    package sample.mybatis.mapper;
    
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    import sample.mybatis.domain.City;
    
    @Mapper
    public interface CityMapper {
    
        @Select("SELECT * FROM CITY WHERE state = #{state}")
        City findByState(@Param("state") String state);
    
    }

    测试类:

    java
    package sample.mybatis.mapper;
    
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.mybatis.spring.boot.test.autoconfigure.MybatisTest;
    import sample.mybatis.domain.City;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import static org.assertj.core.api.Assertions.assertThat;
    
    @RunWith(SpringRunner.class)
    @MybatisTest
    public class CityMapperTest {
    
        @Autowired
        private CityMapper cityMapper;
    
        @Test
        public void findByStateTest() {
            City city = cityMapper.findByState("CA");
            assertThat(city.getName()).isEqualTo("San Francisco");
            assertThat(city.getState()).isEqualTo("CA");
            assertThat(city.getCountry()).isEqualTo("US");
        }
    
    }

    DAO 模式下的测试

    如果你为下面的 DAO 类创建测试,你只需要将 @MybatisTest 和 @Import 添加在你的测试类上。

    DAO 类:

    java
    package sample.mybatis.dao;
    
    import org.apache.ibatis.session.SqlSession;
    import sample.mybatis.domain.City;
    
    import org.springframework.stereotype.Component;
    
    @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);
        }
    
    }

    测试类:

    java
    package sample.mybatis.dao;
    
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.mybatis.spring.boot.test.autoconfigure.MybatisTest;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Import;
    import org.springframework.test.context.junit4.SpringRunner;
    import sample.mybatis.domain.City;
    
    import static org.assertj.core.api.Assertions.assertThat;
    
    @RunWith(SpringRunner.class)
    @MybatisTest
    @Import(CityDao.class)
    public class CityDaoTest {
    
        @Autowired
        private CityDao cityDao;
    
        @Test
        public void selectCityByIdTest() {
            City city = cityDao.selectCityById(1);
            assertThat(city.getName()).isEqualTo("San Francisco");
            assertThat(city.getState()).isEqualTo("CA");
            assertThat(city.getCountry()).isEqualTo("US");
        }
    
    }

    使用真实的数据库

    内嵌的数据库通常在测试上表现良好,因为们很快,且不需要安装一些开发工具。
    然而如果你希望使用真实的数据库,你可以像下面这样使用 @AutoConfigureTestDatabase :

    java
    package sample.mybatis.mapper;
    // ...
    import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
    
    @RunWith(SpringRunner.class)
    @MybatisTest
    @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
    public class CityMapperTest {
        // ...
    }

    避免探测到真实的 @SpringBootApplication

    @MybatisTest 在默认情况下将会探测到带有 @SpringBootApplication 的类。
    因此,由于 bean 定义的一些方法,可能会发生一些意想不到的错误,或者一些不必要的组件被装入 ApplicationContext 。
    为了避免这种情况,我们可以在与测试类相同的包中创建带有 @SpringBootApplication 的类。

    java
    package sample.mybatis.mapper;
    
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    class MapperTestApplication {
    
    }

    与其他 @***Test 一起使用

    如果 @MybatisTest 与其他的 @***Test 一起使用(例如: @WebMvcTest),
    请考虑使用 @AutoConfigureMybatis ,因为不能在同一测试中指定两个或多个@***Test 注解。

    测试的目标类:

    java
    @RestController
    public class PingController {
      PingMapper mapper;
    
      PingController(PingMapper mapper) {
        this.mapper = mapper;
      }
    
      @GetMapping("ping")
      String ping() {
        return mapper.ping();
      }
    }
    java
    @Mapper
    public interface PingMapper {
    @Select("SELECT 'OK'")
      String ping();
    }

    测试类:

    java
    @RunWith(SpringRunner.class)
    @WebMvcTest
    @AutoConfigureMybatis // 替代 @MybatisTest
    public class PingTests {
    
      @Autowired
      private MockMvc mvc;
    
      @Test
      public void ping() throws Exception {
        this.mvc.perform(get("/ping"))
            .andExpect(status().isOk())
            .andExpect(content().string("OK"));
      }
    
    }

    在 JUnit 5 上使用 @MybatisTest

    @MybatisTest 可以在 JUnit 5 上使用:

    java
    @ExtendWith(SpringExtension.class)
    @MybatisTest
    public class CityMapperTest {
        // ...
    }

    自 2.0.1 起, @ExtendWith(SpringExtension.class) 可以像下面这样被忽略:

    java
    @MybatisTest
    public class CityMapperTest {
        // ...
    }

    附录

    导入的自动配置

    @MybatisTest 将会导入以下自动配置的类:

    • org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
    • org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration
    • org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
    • org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
    • org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration
    • org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration
    • org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration
    • org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration
    • org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration
    • org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

    可运行的样例

    项目(为每个类型)提供了两个样例供使用:

    分类 样例 描述
    核心 样例1 展示了最简单的场景,只有一个 mapper 和一个注入 mapper 的组件。这就是我们在“快速入门”部分看到的例子。
    样例2 展示了如何在 XML 文件中使用一个带有语句的 Mapper,并且也有使用 SqlSessionTemplate 的 DAO 的示例。
    JVM 语言 样例3 展示了如何和 kotlin 一同使用。
    样例4 展示了如何和 groovy 一同使用。

    File: .github/workflows/ci.yaml

    name: Java CI

    on: [workflow_dispatch, push, pull_request]

    permissions: read-all

    concurrency:
    group: ${{ github.workflow }}-${{ github.ref }}
    cancel-in-progress: true

    jobs:
    test:
    runs-on: ${{ matrix.os }}
    timeout-minutes: 30
    strategy:
    matrix:
    cache: [maven]
    distribution: [temurin]
    java: [21, 25, 26]
    os: [macos-latest, ubuntu-latest, windows-latest]
    fail-fast: false
    max-parallel: 6
    name: Test JDK ${{ matrix.java }}, ${{ matrix.os }}

    text
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
      - name: Setup Java ${{ matrix.java }} ${{ matrix.distribution }}
        uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6
        with:
          cache: ${{ matrix.cache }}
          distribution: ${{ matrix.distribution }}
          java-version: ${{ matrix.java }}
      - name: Test with Maven
        run: ./mvnw test --batch-mode --no-transfer-progress --show-version -D"license.skip=true"

    File: .github/workflows/cleanup.yaml

    name: Cleanup Old Workflow Runs
    on:
    schedule:
    - cron: '0 0 * * *' # daily at midnight
    workflow_dispatch:

    permissions:
    actions: write

    concurrency:
    group: ${{ github.workflow }}-${{ github.ref }}
    cancel-in-progress: true

    jobs:
    cleanup:
    runs-on: ubuntu-latest
    steps:
    - uses: Mattraks/delete-workflow-runs@0cf693bc9909e5e867ee8f27b813224ba862939c # v2
    with:
    retain_days: 30
    token: ${{ github.token }}


    File: .github/workflows/codeql.yaml

    name: "CodeQL"

    on:
    push:
    branches: [ master ]
    pull_request:
    branches: [ master ]
    schedule:
    - cron: '43 10 * * 2'

    concurrency:
    group: ${{ github.workflow }}-${{ github.ref }}
    cancel-in-progress: true

    jobs:
    analyze:
    name: Analyze
    runs-on: 'ubuntu-latest'
    timeout-minutes: 30
    permissions:
    actions: read
    contents: read
    security-events: write

    text
    steps:
      - name: Checkout
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
    
      - name: Setup Java
        uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6
        with:
          cache: maven
          distribution: 'temurin'
          java-version: 25
    
      - name: Initialize CodeQL
        uses: github/codeql-action/init@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4
        with:
          queries: +security-and-quality
    
      - name: Autobuild
        uses: github/codeql-action/autobuild@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4
    
      - name: Perform CodeQL Analysis
        uses: github/codeql-action/analyze@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4

    File: .github/workflows/coveralls.yaml

    name: Coveralls

    on: [push, pull_request]

    permissions: read-all

    concurrency:
    group: ${{ github.workflow }}-${{ github.ref }}
    cancel-in-progress: true

    jobs:
    coveralls:
    if: github.repository_owner == 'mybatis'
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
    - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
    - name: Setup Java
    uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6
    with:
    cache: maven
    distribution: temurin
    java-version: 25
    - name: Run the build
    run: ./mvnw install --batch-mode --no-transfer-progress --quiet --show-version -Dlicense.skip=true
    - name: Report Coverage to Coveralls for Pull Requests
    if: github.event_name == 'pull_request'
    run: ./mvnw generate-sources jacoco:report coveralls:report --batch-mode --no-transfer-progress -DpullRequest=${{ env.PR_NUMBER }} -DrepoToken=${{ env.GITHUB_TOKEN }} -DserviceName=github
    env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    PR_NUMBER: ${{ github.event.number }}
    - name: Report Coverage to Coveralls for General Push
    if: github.event_name == 'push'
    run: ./mvnw generate-sources jacoco:report coveralls:report --batch-mode --no-transfer-progress -DrepoToken=${{ env.GITHUB_TOKEN }} -DserviceName=github
    env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}


    File: .github/workflows/site.yaml

    name: Site

    on:
    push:
    branches:
    - site

    permissions:
    contents: write

    concurrency:
    group: ${{ github.workflow }}-${{ github.ref }}
    cancel-in-progress: true

    jobs:
    build:
    if: github.repository_owner == 'mybatis' && ! contains(toJSON(github.event.head_commit.message), '[maven-release-plugin]')
    runs-on: ubuntu-latest
    timeout-minutes: 60
    steps:
    - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
    - name: Setup Java
    uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6
    with:
    cache: maven
    distribution: temurin
    java-version: 25
    - name: Build site
    run: ./mvnw site site:stage --batch-mode --no-transfer-progress --settings ./.mvn/settings.xml --show-version -Dlicense.skip=true -DskipTests
    env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    NVD_API_KEY: ${{ secrets.NVD_API_KEY }}
    - name: Deploy Site to gh-pages
    uses: JamesIves/github-pages-deploy-action@fa24774553152dd7873cd16ebd8d959b010c5445 # v4
    with:
    branch: gh-pages
    folder: target/spring-boot-starter.git


    File: .github/workflows/sonar.yaml

    name: SonarCloud

    on:
    push:
    branches:
    - master

    permissions: read-all

    concurrency:
    group: ${{ github.workflow }}-${{ github.ref }}
    cancel-in-progress: true

    env:
    SONAR_ORGANIZATION: mybatis
    SONAR_PROJECT_KEY: spring-boot-starter

    jobs:
    build:
    if: github.repository_owner == 'mybatis'
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
    - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
    with:
    # Disabling shallow clone is recommended for improving relevancy of reporting
    fetch-depth: 0
    - name: Setup Java
    uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6
    with:
    cache: maven
    distribution: temurin
    java-version: 25
    - name: Set SONAR_SCANNER_JAVA_OPTS
    run: echo "SONAR_SCANNER_JAVA_OPTS=-Xmx512m" >> ${GITHUB_ENV}
    - name: Analyze with SonarCloud
    run: ./mvnw verify jacoco:report sonar:sonar --batch-mode --no-transfer-progress --show-version -Dlicense.skip=true -Dsonar.host.url=https://sonarcloud.io -Dsonar.organization=${{ env.SONAR_ORGANIZATION }} -Dsonar.projectKey=${{ env.SONAR_ORGANIZATION }}_${{ env.SONAR_PROJECT_KEY }} -Dsonar.scanner.skipJreProvisioning=true -Dsonar.token=${{ env.SONAR_TOKEN }}
    env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}


    File: .github/workflows/sonatype.yaml

    name: Sonatype

    on:
    push:
    branches:
    - master

    permissions: read-all

    concurrency:
    group: ${{ github.workflow }}-${{ github.ref }}
    cancel-in-progress: true

    jobs:
    build:
    if: github.repository_owner == 'mybatis' && ! contains(toJSON(github.event.head_commit.message), '[maven-release-plugin]')
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
    - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
    - name: Setup Java
    uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6
    with:
    cache: maven
    distribution: temurin
    java-version: 25
    - name: Deploy to Sonatype
    run: ./mvnw deploy --batch-mode --no-transfer-progress --settings ./.mvn/settings.xml --show-version -Dlicense.skip=true -DskipTests
    env:
    CI_DEPLOY_USERNAME: ${{ secrets.CI_DEPLOY_USERNAME }}
    CI_DEPLOY_PASSWORD: ${{ secrets.CI_DEPLOY_PASSWORD }}


    File: .github/workflows/support.yaml

    Licensed under the Apache License, Version 2.0 (the "License");

    you may not use this file except in compliance with the License.

    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software

    distributed under the License is distributed on an "AS IS" BASIS,

    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

    See the License for the specific language governing permissions and

    limitations under the License.

    name: Spring Boot Support Samples

    on: [push, pull_request]

    permissions: read-all

    jobs:
    test:
    runs-on: ${{ matrix.os }}
    strategy:
    matrix:
    cache: [maven]
    distribution: ['zulu']
    java: [21, 25]
    os: [macos-latest, ubuntu-latest, windows-latest]
    fail-fast: false
    max-parallel: 5
    name: Test JDK ${{ matrix.java }}, ${{ matrix.os }}

    text
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
      - name:  Setup Java ${{ matrix.java }} ${{ matrix.distribution }}
        uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6
        with:
          cache: ${{ matrix.cache }}
          distribution: ${{ matrix.distribution }}
          java-version: ${{ matrix.java }}
      - name: Test with Spring Boot Latest
        run: |
          ./mvnw package
          ./mybatis-spring-boot-samples/run_fatjars.sh