Introduce dependencies
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
@ConditionalOnSingleCandidate(DataSource.class)
single source of truth
SqlSessionFactory: automatically configured
@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);data source
@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 is automatically configured to combine SqlSession
@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);
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 (annotation)
logger.debug("Searching for mappers annotated with @Mapper");
Find all interfaces with @Mapper
- Mapper: As long as the interface we write to operate MyBatis is marked with @Mapper, it will be automatically scanned in
classpath:
classpath
In Spring Boot, the class path/java/
refers to both the directory plus the directory of the program before packaging /resource
, and the directory generated by the program after packaging /classes/
. The two actually refer to the same directory, and the contents of the files contained in it are exactly the same.