一、添加依赖

版本对应

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
2.0 (EOL) 2.0 2.0 or 2.1 8 or higher
1.3 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
  1. <dependency>
  2. <groupId>org.mybatis.spring.boot</groupId>
  3. <artifactId>mybatis-spring-boot-starter</artifactId>
  4. <version>2.1.3</version>
  5. </dependency>

二、SpringBoot整合Mybatis

  • 自动扫描存在的Datesource
  • 通过SqlSessionFactoryBean使用 DataSource 创建和实例化一个 SqlSessionFactory
  • 从SqlSessionFactory创建和实例化一个 SqlSessionTemplate
  • 自动扫描mapper,像SqlSessionTemplate并且注册到Spring context以便能够自动注入。 ```java @Mapper public interface CityMapper {

    @Select(“SELECT * FROM CITY WHERE state = #{state}”) City findByState(@Param(“state”) String state);

}

//使用时直接 private final CityMapper cityMapper;


**application.properties/application.yml  **中mybatis的配置


| 属性 | 描述 |
| --- | --- |
| config-location | MyBatis.xml的全局配置文件 |
| check-config-location | 是否对mybatis.xml进行检查 |
| mapper-locations | mapper接口对应的mapper.xml文件 |
| type-aliases-package | 包扫描别名. (分割符:, ",; \\t\\n ") |
| type-aliases-super-type | 用于过滤类型别名的超类.如果没有特殊设置,如果未指定,则MyBatis将所有从type-aliases-package搜索的类当作类型别名。 |
| type-handlers-package | 处理类型的包扫描(包分割 :, ",; \\t\\n ") |
| executor-type | Executor type的类型选择: SIMPLE, REUSE, BATCH |
| default-scripting-language-driver | 默认脚本语言类,需要mybatis-spring 2.0.2+的支持。 |
| configuration-properties | MyBatis configuration外部部署引用,指定的属性可用作MyBatis配置文件和Mapper文件上的占位符,详细看 [MyBatis reference page](http://www.mybatis.org/mybatis-3/configuration.html#properties). |
| lazy-initialization | 是否懒加载, true 进行懒加载 需要mybatis-spring 2.0.2+的支持。 |
| configuration.* | <br /><br />配置 MyBatis Core.提供的Configuration bean 。可参考[MyBatis reference page](http://www.mybatis.org/mybatis-3/configuration.html#settings)<br />**注意:**不能和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](http://www.mybatis.org/thymeleaf-scripting/user-guide.html#_configuration_properties)<br />. |
| scripting-language-driver.freemarker.* | Properties keys for FreeMarkerLanguageDriverConfig bean provided by MyBatis FreeMarker. About available nested properties see the [MyBatis FreeMarker reference page](http://www.mybatis.org/freemarker-scripting/#Configuration)<br />. 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](http://www.mybatis.org/velocity-scripting/#Configuration)<br />. This feature requires to use together with mybatis-velocity 2.1.0+. |



**案例**
```yaml
# MyBatis配置
mybatis:
  # 搜索指定包别名,mapper接口所在的位置
  typeAliasesPackage: cn.ym.project.**.domain
  # 配置mapper的扫描,找到所有的mapper.xml映射文件
  mapperLocations: classpath:mybatis/**/*Mapper.xml
  # 加载全局的配置文件
  configLocation: classpath:mybatis/mybatis-config.xml

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="cacheEnabled"             value="true" />  <!-- 全局映射器启用缓存 -->
        <setting name="useGeneratedKeys"         value="true" />  <!-- 允许 JDBC 支持自动生成主键 -->
        <setting name="defaultExecutorType"      value="REUSE" /> <!-- 配置默认的执行器 -->
        <setting name="logImpl"                  value="SLF4J" /> <!-- 指定 MyBatis 所用日志的具体实现 -->
        <!-- <setting name="mapUnderscoreToCamelCase" value="true"/>  驼峰式命名 -->
    </settings>
</configuration>

JAVA实现自定义配置


MyBatis-Spring-Boot-Starter 会扫描实现了 ConfigurationCustomizer的接口,自动的定制mybatis配置

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

SpringBootVFS

MyBatis-Spring-Boot-Starter提供了SpringBootVFS作为VFS的实现类。 VFS用于从应用程序(或应用程序服务器)搜索类(例如,别名类型的目标类,类型处理程序类)。 如果使用可执行jar运行Spring Boot应用程序,则需要使用SpringBootVFS。 MyBatis-Spring-Boot-Starter提供的自动配置功能会自动使用它,但不会通过手动配置自动使用
不是很懂,但是按照下面这样写。

@Configuration
public class MyBatisConfig {

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

待补充….

探测mybatis的组件

  • Interceptor
  • TypeHandler
  • LanguageDriver (Requires to use together with 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;
    }  
    }
    
    如果探测语言驱动只有一个,会自动设置为默认。

    三、spring boot 实战整合

    3.1 添加依赖和yml配置

!-- SpringBoot集成mybatis框架 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
          <!-- <mybatis.spring.boot.starter.version>1.3.2</mybatis.spring.boot.starter.version>-->
            <version>${mybatis.spring.boot.starter.version}</version>
        </dependency>
# MyBatis配置
mybatis:
  # 搜索指定包别名 最后胜生成的是class,自动加载的时候变成这样classpath*:cn/ym/project/**/domain/**/*.class
  typeAliasesPackage: cn.ym.project.**.domain
  # 配置mapper的扫描,找到所有的mapper.xml映射文件
  mapperLocations: classpath:mybatis/**/*Mapper.xml
  # 加载全局的配置文件
  configLocation: classpath:mybatis/mybatis-config.xml

mybatis-config.xml 全局配置

<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE configuration
                PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
    <setting name="cacheEnabled"             value="true" />  <!-- 全局映射器启用缓存 -->
    <setting name="useGeneratedKeys"         value="true" />  <!-- 允许 JDBC 支持自动生成主键 -->
    <setting name="defaultExecutorType"      value="REUSE" /> <!-- 配置默认的执行器 -->
    <setting name="logImpl"                  value="SLF4J" /> <!-- 指定 MyBatis 所用日志的具体实现 -->
    <!-- <setting name="mapUnderscoreToCamelCase" value="true"/>  驼峰式命名 -->
</settings>
</configuration>

目录如下:和yml中configLocation的路径对应
image.png

MybatisConfig类编写,自动扫描mapper接口

package cn.ym.framework.config;

import org.apache.ibatis.io.VFS;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * Mybatis支持*匹配扫描包
 * 
 * @author ym
 */
@Configuration
public class MyBatisConfig
{
    /**spring 的配置,问题,直接能够读取到yml中的配置
     * */
    @Autowired
    private Environment env;

    static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
    static final Logger LOG = LoggerFactory.getLogger(MyBatisConfig.class);

    //将查找所有domain的包,并且返回所有的包名:
    // 如下:cn.ym.project.system.domain,cn.ym.project.competition.domain
    public static String setTypeAliasesPackage(String typeAliasesPackage)
    {
        ////获取Spring资源解析器
        ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver();
        //创建Spring中用来读取class的工厂
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
        List<String> allResult = new ArrayList<String>();
        try
        {
            for (String aliasesPackage : typeAliasesPackage.split(","))
            {
                List<String> result = new ArrayList<String>();
                //获得类路径,classpath*: + 类名转化为资源路径/**/*.class
                aliasesPackage = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                        + ClassUtils.convertClassNameToResourcePath(aliasesPackage.trim()) + "/" + DEFAULT_RESOURCE_PATTERN;

                Resource[] resources = resolver.getResources(aliasesPackage);
                if (resources != null && resources.length > 0)
                {
                    MetadataReader metadataReader = null;
                    for (Resource resource : resources)
                    {
                        if (resource.isReadable())
                        {
                            metadataReader = metadataReaderFactory.getMetadataReader(resource);
                            try
                            {

                                result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());
                            }
                            catch (ClassNotFoundException e)
                            {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                if (result.size() > 0)
                {
                    //去重
                    HashSet<String> hashResult = new HashSet<String>(result);
                    allResult.addAll(hashResult);
                }
            }
            if (allResult.size() > 0)
            {
                typeAliasesPackage = String.join(",", (String[]) allResult.toArray(new String[0]));

            }
            else
            {
                throw new RuntimeException("mybatis typeAliasesPackage 路径扫描错误,参数typeAliasesPackage:" + typeAliasesPackage + "未找到任何包");
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return typeAliasesPackage;
    }

    /***
     * 配置mybati的sqlSessionFactory
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception
    {
        String typeAliasesPackage = env.getProperty("mybatis.typeAliasesPackage");
        String mapperLocations = env.getProperty("mybatis.mapperLocations");
        String configLocation = env.getProperty("mybatis.configLocation");
        //获得所有存在domain的全限定包名
        typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage);
        //进行包扫描,还是不懂,按照这个写
        VFS.addImplClass(SpringBootVFS.class);
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        //自动扫描包,添加到sessionFactory中...
        sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
        return sessionFactory.getObject();
    }
}

如果不编写Config,那么需要在mapper接口上增加 @Mapper。