mybatis与spring的整合之SqlSessionFactoryBean

mybatis与spring的整合之SqlSessionFactoryBean

  • SqlSessionFactoryBean配置
    • 注入mapperLocations
    • 注入configLocation
    • mapperLocations与configLocation比较
  • SqlSessionFactoryBean源码跟踪
    • 实现了FactoryBean接口
    • 实现了InitializingBean接口
      • dataSource不能为空
      • sqlSessionFactoryBuilder不能为空
      • configuration与configLocation
    • 关键方法buildSqlSessionFactory
      • 构建Configuration对象
      • 设置数据源dataSource
      • 解析configLocation
        • XMLConfigBuilder.parse解析配置文件
      • 解析mapperLocations
        • XMLMapperBuilder.parse解析sql配置
      • 设置其他属性
      • 构建SqlSessionFactory对象

解释: MapperFactoryBean是将映射接口 注册进spring,详见 mybatis与spring的整合之MapperFactoryBean,而 SqlSessionFactoryBean则是 解析映射接口对应的sql配置文件(xml文件)

SqlSessionFactoryBean配置

在基本的 MyBatis 中,session 工厂可以使用 SqlSessionFactoryBuilder 来创建。而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean 来替代。
SqlSessionFactoryBean引入sql配置文件有两种形式

注入mapperLocations

mybatis与spring的整合之SqlSessionFactoryBean_第1张图片
sql配置文件






	t.id,
	t.app_name,
	t.title,
	t.`order`,
	t.address_type,
	t.address_list



	.
	.
	.


引入


	
	

Resource[] mapperLocations
spring内置的属性编辑器会将mybatis-mapper/*.xml转换为Resource数组

注入configLocation

在这里插入图片描述
configuration配置文件





	/*
		
	*/

	
	
		
		
		
		
		
	

引入


	
	
	

mapperLocations与configLocation比较

mapperLocations仅仅是sql配置文件,会被解析放入Configuration
configLocation可以设置其他东西,比如二级缓存、实体类别名数据源(DataSource)等,可以配置多个config.xml实现多数据源配置。它会被解析为Configuration对象,这是构建SqlSessionFactory所必须的。
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息,这里可直接看官网:configuration配置

SqlSessionFactoryBean源码跟踪

mybatis与spring的整合之SqlSessionFactoryBean_第2张图片

实现了FactoryBean接口

SqlSessionFactoryBean实现了FactoryBean,重写了getObject接口 ,通过该方法返回SqlSessionFactory对象

public SqlSessionFactory getObject() throws Exception {
  if (this.sqlSessionFactory == null) {
    afterPropertiesSet();
  }
  return this.sqlSessionFactory;
}

实现了InitializingBean接口

SqlSessionFactoryBean实现了InitializingBean接口,重写了afterPropertiesSet方法

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

dataSource不能为空

dataSource必须手动显示注入

sqlSessionFactoryBuilder不能为空

sqlSessionFactoryBuilder初始化为SqlSessionFactoryBuilder,可不用手动注入

configuration与configLocation

configurationbeanconfigLocation配置文件,两者不能同时配置

关键方法buildSqlSessionFactory

构建Configuration对象

  1. 通过自定义的configuration,一个bean
  2. 通过自定义的configLocation,一个xml配置文件
  3. 以上都没有的话,则new一个configuration对象
Configuration configuration;
XMLConfigBuilder xmlConfigBuilder = null;
if (this.configuration != null) {
  configuration = this.configuration;
  if (configuration.getVariables() == null) {
    configuration.setVariables(this.configurationProperties);
  } else if (this.configurationProperties != null) {
    configuration.getVariables().putAll(this.configurationProperties);
  }
} else if (this.configLocation != null) {
  xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
  configuration = xmlConfigBuilder.getConfiguration();
} else {
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
  }
  configuration = new Configuration();
  if (this.configurationProperties != null) {
    configuration.setVariables(this.configurationProperties);
  }
}

设置数据源dataSource

configuration.setEnvironment(new Environment(this.environment, this.transactionFactory, this.dataSource));

解析configLocation

if (xmlConfigBuilder != null) {
  try {
    xmlConfigBuilder.parse();
    if (LOGGER.isDebugEnabled()) {
      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();
  }
}

如果configLocation属性值不为空,则xmlConfigBuilder会通过configLocation对象构建,这里就会开始解析

XMLConfigBuilder.parse解析配置文件

从根目录configuration开始解析,后面就不具体看了

public Configuration parse() {
  if (parsed) {
    throw new BuilderException("Each XMLConfigBuilder can only be used once.");
  }
  parsed = true;
  parseConfiguration(parser.evalNode("/configuration"));
  return configuration;
}

解析mapperLocations

如果mapperLocations属性值不为空,则在这里开始解析

if (!isEmpty(this.mapperLocations)) {
  for (Resource mapperLocation : this.mapperLocations) {
    if (mapperLocation == null) {
      continue;
    }

    try {
      XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
          configuration, mapperLocation.toString(), configuration.getSqlFragments());
      xmlMapperBuilder.parse();
    } catch (Exception e) {
      throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
    } finally {
      ErrorContext.instance().reset();
    }
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Parsed mapper file: '" + mapperLocation + "'");
    }
  }
}

XMLMapperBuilder.parse解析sql配置

从根目录mapper开始解析,后面就不具体看了

public void parse() {
  if (!configuration.isResourceLoaded(resource)) {
    configurationElement(parser.evalNode("/mapper"));
    configuration.addLoadedResource(resource);
    bindMapperForNamespace();
  }
  // 解析ResultMap
  parsePendingResultMaps();
  // 二级缓存
  parsePendingCacheRefs();
  // sql语句
  parsePendingStatements();
}

设置其他属性

SqlSessionFactory可以注入一些其他属性,比如缓存、别名等,有的话都会被设置进configuration对象中
mybatis与spring的整合之SqlSessionFactoryBean_第3张图片

构建SqlSessionFactory对象

return this.sqlSessionFactoryBuilder.build(configuration);

SqlSessionFactoryBuilder.build,构建的是DefaultSqlSessionFactory

public SqlSessionFactory build(Configuration config) {
  return new DefaultSqlSessionFactory(config);
}

你可能感兴趣的:(mybatis源码)