SpringBoot-数据访问-整合MyBatis-配置版

引入依赖


    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    2.1.4

SpringBoot-数据访问-整合MyBatis-配置版_第1张图片

SpringBoot-数据访问-整合MyBatis-配置版_第2张图片

@ConditionalOnSingleCandidate(DataSource.class)

单一数据源

SpringBoot-数据访问-整合MyBatis-配置版_第3张图片

 SqlSessionFactory: 自动配置好了

  @Bean
  @ConditionalOnMissingBean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    factory.setDataSource(dataSource);
    factory.setVfs(SpringBootVFS.class);
    //xxxxxxxxxxx
}

DataSource dataSource
factory.setDataSource(dataSource);

数据源


SpringBoot-数据访问-整合MyBatis-配置版_第4张图片

  @Bean
  @ConditionalOnMissingBean
  public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    ExecutorType executorType = this.properties.getExecutorType();
    if (executorType != null) {
      return new SqlSessionTemplate(sqlSessionFactory, executorType);
    } else {
      return new SqlSessionTemplate(sqlSessionFactory);
    }
  }

 SqlSession:自动配置了 SqlSessionTemplate 组合了SqlSession

SpringBoot-数据访问-整合MyBatis-配置版_第5张图片


SpringBoot-数据访问-整合MyBatis-配置版_第6张图片

  @org.springframework.context.annotation.Configuration
  @Import(AutoConfiguredMapperScannerRegistrar.class)
  @ConditionalOnMissingBean({ MapperFactoryBean.class, MapperScannerConfigurer.class })
  public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {

    @Override
    public void afterPropertiesSet() {
      logger.debug(
          "Not found configuration for registering mapper bean using @MapperScan, MapperFactoryBean and MapperScannerConfigurer.");
    }

  }

 @Import(AutoConfiguredMapperScannerRegistrar.class);

SpringBoot-数据访问-整合MyBatis-配置版_第7张图片

public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar {

    private BeanFactory beanFactory;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

      if (!AutoConfigurationPackages.has(this.beanFactory)) {
        logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.");
        return;
      }

      logger.debug("Searching for mappers annotated with @Mapper");

    //xxxxxxxxxxxxx

    }

}

AnnotationMetadata(注解)

logger.debug("Searching for mappers annotated with @Mapper");

找到所有带有@Mapper的接口

  • Mapper: 只要我们写的操作MyBatis的接口标注了 @Mapper 就会被自动扫描进来

classpath:

classpath类路径在 Spring Boot 中既指程序在打包前的/java/目录加上/resource目录,也指程序在打包后生成的/classes/目录。两者实际上指的是同一个目录,里面包含的文件内容一模一样。

你可能感兴趣的:(mybatis,spring,boot,java)