MyBatis中SqlSessionFactory

SqlSessionFactory的作用

根据mapper配置文件解析出dao与具体jdbc操作、resultMap与实体类等的映射关系

1.SpringBoot整合MyBatis如何加载SqlSessionFactory

1.1 SpringBoot自动装配Spring.factories文件

Spring.factories文件中EnableAutoConfiguration对应的值MybatisAutoConfiguration

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration,\
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

1.2 读取yml配置文件中的mybatis配置

mybatis:
  mapper-locations: classpath:com/sunpy/demo/mapper/*Mapper.xml
  type-aliases-package: com.sunpy.demo.entity

MybatisAutoConfiguration中注入MybatisProperties配置类,实现:
image

@EnableConfigurationProperties这个注解的作用会将使用 @ConfigurationProperties的类进行了一次注入。

MybatisProperties类使用@ConfigurationProperties映射属性:
mybatis.mapper-locations 映射为 mapperLocations字段
mybatis.type-aliases-package 映射为 typeAliasesPackage字段

image

1.3 MybatisAutoConfiguration中SqlSessionFactory

实现的功能:
① 使用SqlSessionFactoryBean类,这个类实现了FactoryBean接口,通过getObject方法实例化SqlSessionFactory。说明SqlSessionFactoryBean类主要作用是实例化SqlSessionFactory。
② 设置datasource数据源。
③ 扫描映射的po类。
④ 扫描加载mapper中的xml文件。

@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
	// 设置数据源DataSource
	SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
	factory.setDataSource(dataSource);
	factory.setVfs(SpringBootVFS.class);
	// 设置总配置文件,mybatis-config.xml
	if (StringUtils.hasText(this.properties.getConfigLocation())) {
	  factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
	}
	applyConfiguration(factory);
	if (this.properties.getConfigurationProperties() != null) {
	  factory.setConfigurationProperties(this.properties.getConfigurationProperties());
	}
	if (!ObjectUtils.isEmpty(this.interceptors)) {
	  factory.setPlugins(this.interceptors);
	}
	if (this.databaseIdProvider != null) {
	  factory.setDatabaseIdProvider(this.databaseIdProvider);
	}
	// 读取MybatisProperties中属性值,设置mybatis自动扫描到自定义的POJO
	if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
	  factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
	}
	if (this.properties.getTypeAliasesSuperType() != null) {
	  factory.setTypeAliasesSuperType(this.properties.getTypeAliasesSuperType());
	}
	if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
	  factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
	}
	if (!ObjectUtils.isEmpty(this.typeHandlers)) {
	  factory.setTypeHandlers(this.typeHandlers);
	}
	// 读取MybatisProperties中属性值,设置mapper-locations,扫描mapper的xml文件
	if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
	  factory.setMapperLocations(this.properties.resolveMapperLocations());
	}
	Set<String> factoryPropertyNames = Stream
		.of(new BeanWrapperImpl(SqlSessionFactoryBean.class).getPropertyDescriptors()).map(PropertyDescriptor::getName)
		.collect(Collectors.toSet());
	Class<? extends LanguageDriver> defaultLanguageDriver = this.properties.getDefaultScriptingLanguageDriver();
	if (factoryPropertyNames.contains("scriptingLanguageDrivers") && !ObjectUtils.isEmpty(this.languageDrivers)) {
	  // Need to mybatis-spring 2.0.2+
	  factory.setScriptingLanguageDrivers(this.languageDrivers);
	  if (defaultLanguageDriver == null && this.languageDrivers.length == 1) {
		defaultLanguageDriver = this.languageDrivers[0].getClass();
	  }
	}
	if (factoryPropertyNames.contains("defaultScriptingLanguageDriver")) {
	  // Need to mybatis-spring 2.0.2+
	  factory.setDefaultScriptingLanguageDriver(defaultLanguageDriver);
	}
	// 创建SqlSessionFactory对象
	return factory.getObject();
}

1.4 注册SqlSessionFactory类到spring的逻辑

自动装配的逻辑中使用ConfigurationClassPostProcessor这个处理@Configuration注解的后置处理器,使用registerBeanDefinition方法,将当前的SqlSessionFactory类放入beanDefinitionMap中。

2. 细看SqlSessionFactoryBean实例化SqlSessionFactory

image

2.1 调用getObject方法实例化SqlSessionFactory

@Override
public SqlSessionFactory getObject() throws Exception {
	if (this.sqlSessionFactory == null) {
	  afterPropertiesSet();
	}
 
	return this.sqlSessionFactory;
}
 
@Override
public void afterPropertiesSet() throws Exception {
	notNull(dataSource, "Property 'dataSource' is required");
	notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
	state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
		"Property 'configuration' and 'configLocation' can not specified with together");
 
	this.sqlSessionFactory = buildSqlSessionFactory();
}

2.2 核心实现,委派给buildSqlSessionFactory()方法,构建SqlSessionFactory对象

  • 解析this.typeAliasesPackage,扫描到自定义的POJO,存放到this.typeAliases
  • 遍历mapper-locations,扫描mapper的所有xml文件,解析xml文件
protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
 
    final Configuration targetConfiguration;
 
    XMLConfigBuilder xmlConfigBuilder = null;
    if (this.configuration != null) {
      targetConfiguration = this.configuration;
      if (targetConfiguration.getVariables() == null) {
        targetConfiguration.setVariables(this.configurationProperties);
      } else if (this.configurationProperties != null) {
        targetConfiguration.getVariables().putAll(this.configurationProperties);
      }
    } else if (this.configLocation != null) {
      xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
      targetConfiguration = xmlConfigBuilder.getConfiguration();
    } else {
      LOGGER.debug(
          () -> "Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
      targetConfiguration = new Configuration();
      Optional.ofNullable(this.configurationProperties).ifPresent(targetConfiguration::setVariables);
    }
 
    Optional.ofNullable(this.objectFactory).ifPresent(targetConfiguration::setObjectFactory);
    Optional.ofNullable(this.objectWrapperFactory).ifPresent(targetConfiguration::setObjectWrapperFactory);
    Optional.ofNullable(this.vfs).ifPresent(targetConfiguration::setVfsImpl);
	// 扫描到自定义的POJO,存放到this.typeAliases
    if (hasLength(this.typeAliasesPackage)) {
      scanClasses(this.typeAliasesPackage, this.typeAliasesSuperType).stream()
          .filter(clazz -> !clazz.isAnonymousClass()).filter(clazz -> !clazz.isInterface())
          .filter(clazz -> !clazz.isMemberClass()).forEach(targetConfiguration.getTypeAliasRegistry()::registerAlias);
    }
 
    if (!isEmpty(this.typeAliases)) {
      Stream.of(this.typeAliases).forEach(typeAlias -> {
        targetConfiguration.getTypeAliasRegistry().registerAlias(typeAlias);
        LOGGER.debug(() -> "Registered type alias: '" + typeAlias + "'");
      });
    }
 
    if (!isEmpty(this.plugins)) {
      Stream.of(this.plugins).forEach(plugin -> {
        targetConfiguration.addInterceptor(plugin);
        LOGGER.debug(() -> "Registered plugin: '" + plugin + "'");
      });
    }
 
    if (hasLength(this.typeHandlersPackage)) {
      scanClasses(this.typeHandlersPackage, TypeHandler.class).stream().filter(clazz -> !clazz.isAnonymousClass())
          .filter(clazz -> !clazz.isInterface()).filter(clazz -> !Modifier.isAbstract(clazz.getModifiers()))
          .forEach(targetConfiguration.getTypeHandlerRegistry()::register);
    }
 
    if (!isEmpty(this.typeHandlers)) {
      Stream.of(this.typeHandlers).forEach(typeHandler -> {
        targetConfiguration.getTypeHandlerRegistry().register(typeHandler);
        LOGGER.debug(() -> "Registered type handler: '" + typeHandler + "'");
      });
    }
 
    targetConfiguration.setDefaultEnumTypeHandler(defaultEnumTypeHandler);
 
    if (!isEmpty(this.scriptingLanguageDrivers)) {
      Stream.of(this.scriptingLanguageDrivers).forEach(languageDriver -> {
        targetConfiguration.getLanguageRegistry().register(languageDriver);
        LOGGER.debug(() -> "Registered scripting language driver: '" + languageDriver + "'");
      });
    }
    Optional.ofNullable(this.defaultScriptingLanguageDriver)
        .ifPresent(targetConfiguration::setDefaultScriptingLanguage);
 
    if (this.databaseIdProvider != null) {// fix #64 set databaseId before parse mapper xmls
      try {
        targetConfiguration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
      } catch (SQLException e) {
        throw new NestedIOException("Failed getting a databaseId", e);
      }
    }
 
    Optional.ofNullable(this.cache).ifPresent(targetConfiguration::addCache);
 
    if (xmlConfigBuilder != null) {
      try {
        xmlConfigBuilder.parse();
        LOGGER.debug(() -> "Parsed configuration file: '" + this.configLocation + "'");
      } catch (Exception ex) {
        throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
      } finally {
        ErrorContext.instance().reset();
      }
    }
 
    targetConfiguration.setEnvironment(new Environment(this.environment,
        this.transactionFactory == null ? new SpringManagedTransactionFactory() : this.transactionFactory,
        this.dataSource));
	// 遍历mapper-locations,扫描mapper的所有xml文件
    if (this.mapperLocations != null) {
      if (this.mapperLocations.length == 0) {
        LOGGER.warn(() -> "Property 'mapperLocations' was specified but matching resources are not found.");
      } else {
        for (Resource mapperLocation : this.mapperLocations) {
          if (mapperLocation == null) {
            continue;
          }
          try {
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
                targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
			// 解析mapper的xml文件
            xmlMapperBuilder.parse();
          } catch (Exception e) {
            throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
          } finally {
            ErrorContext.instance().reset();
          }
          LOGGER.debug(() -> "Parsed mapper file: '" + mapperLocation + "'");
        }
      }
    } else {
      LOGGER.debug(() -> "Property 'mapperLocations' was not specified.");
    }
 
    return this.sqlSessionFactoryBuilder.build(targetConfiguration);
}

3. 细看this.typeAliasesPackage指定的扫描po类加载存放到this.typeAliases

scanClasses(this.typeAliasesPackage, this.typeAliasesSuperType).stream()
          .filter(clazz -> !clazz.isAnonymousClass()).filter(clazz -> !clazz.isInterface())
          .filter(clazz -> !clazz.isMemberClass()).forEach(targetConfiguration.getTypeAliasRegistry()::registerAlias);

scanClasses实现

// 扫描指定packagePatterns路径下的类
private Set<Class<?>> scanClasses(String packagePatterns, Class<?> assignableType) throws IOException {
	Set<Class<?>> classes = new HashSet<>();
	// 根据指定的标记将字符串转换为字符串数组
	String[] packagePatternArray = tokenizeToStringArray(packagePatterns,
		ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
	for (String packagePattern : packagePatternArray) {
	// 加载拼接的指定路径下的所有类
	  Resource[] resources = RESOURCE_PATTERN_RESOLVER.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
		  + ClassUtils.convertClassNameToResourcePath(packagePattern) + "/**/*.class");
	  for (Resource resource : resources) {
		try {
		  ClassMetadata classMetadata = METADATA_READER_FACTORY.getMetadataReader(resource).getClassMetadata();
		  Class<?> clazz = Resources.classForName(classMetadata.getClassName());
		  // 搜集加载的类
		  if (assignableType == null || assignableType.isAssignableFrom(clazz)) {
			classes.add(clazz);
		  }
		} catch (Throwable e) {
		  LOGGER.warn(() -> "Cannot load the '" + resource + "'. Cause by " + e.toString());
		}
	  }
	}
	return classes;
}

4. 细看遍历mapper-locations,扫描mapper的所有xml文件,解析xml文件

for (Resource mapperLocation : this.mapperLocations) {
	if (mapperLocation == null) {
		continue;
	}
	try {
		XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
			targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
		xmlMapperBuilder.parse();
	} catch (Exception e) {
		throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
	} finally {
		ErrorContext.instance().reset();
	}
	LOGGER.debug(() -> "Parsed mapper file: '" + mapperLocation + "'");
}

技术收获

1. 根据指定的标记将字符串转换为字符串数组

String[] packagePatternArray = tokenizeToStringArray(packagePatterns,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);

2. 加载指定路径下的所有类

Resource[] resources = RESOURCE_PATTERN_RESOLVER.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
+ ClassUtils.convertClassNameToResourcePath(packagePattern) + "/
/*.class");**

3. 解析加载xml文件

xmlMapperBuilder.parse();

posted @ 2023-08-13 18:42  sunpeiyu  阅读(463)  评论(0编辑  收藏  举报