Mybatisi和Spring整合原始碼分析

語言: CN / TW / HK

一、MybatisSpring的使用

1.建立 Maven 工程。

2.新增依賴,程式碼如下

<dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.7-ybe</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.6-ybe</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.20</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.16</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.3.16</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.8</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.20.RELEASE</version>
    </dependency>

3.新增實體如下,

package com.ybe.entity;

import java.io.Serializable;

public class Book implements Serializable {
    int id;
    double price;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

4.新增 Mapper介面以及BookMapper.xml檔案,

public interface BookMapper {

     Book getBook(@Param("id") int id);
}

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.ybe.mapper.BookMapper">
    <cache></cache>
    <select id="getBook" resultType="com.ybe.entity.Book">
        select * from book where id = #{id}
    </select>
</mapper>

5.新增 BookService 和 BookServiceImpl程式碼如下,

package com.ybe.service;

import com.ybe.entity.Book;

public interface BookSerivce {
    Book getBook(int id);
}

package com.ybe.service.impl;

import com.ybe.entity.Book;
import com.ybe.mapper.BookMapper;
import com.ybe.service.BookSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BookServiceImpl implements BookSerivce {
    @Autowired
    BookMapper bookMapper;
    public Book getBook(int id) {
        return bookMapper.getBook(id);
    }
}

6.新增配置類,程式碼如下

package com.ybe.config;

@Configuration
@MapperScan(basePackages = {"com.ybe.mapper"})
@ComponentScan(basePackages = {"com.ybe"})
public class MyBatisConfig {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setConfigLocation(new ClassPathResource("mybatis.xml"));
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
        .getResources("classpath:com/ybe/mapper/*.xml"));
        factoryBean.setTypeAliases(Book.class);
        return factoryBean;
    }

    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername("xxx");
        dataSource.setPassword("xxx");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/aopTest?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8");
        return dataSource;
    }

    @Bean
    public DataSourceTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}

7.新增主類程式碼,程式碼如下

AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext(MyBatisConfig.class);
BookSerivce bookSerivce = configApplicationContext.getBean(BookSerivce.class);
Book book = bookSerivce.getBook(1);
System.out.println(book.getId());

二、Mybatis和Spring的整合

​ 因為Mybatis中使用的是Mapper.class 介面來找到資料庫sql語句,並且是通過SqlSessionFactory的SqlSession來連線資料庫和執行Sql語句的。所以Mybatis和Spring的整合,其實就是把Mybatis的SqlSessionFactory類和Mapper.Class介面注入到SpringIOC中。並且SqlSessionFactory類中的事務管理物件(SpringManagedTransactionFactory )會整合Spring的事務。

​ 整個整合的過程分為兩部分,第一部分 Mapper介面注入;第二部分 SqlSessionFactoryBean 注入。

2.1 Mapper 介面注入

​ 試想一下我們在寫Mapper介面的時候並沒有寫實現類,只是寫了Mapper.xml檔案。那在注入到Spring容器中,具體的實現類是啥?我這裡直接給答案,Mapper介面在Spring容器中對應的實現類是一個MapperFactoryBean 的類,最終存在beanFactory.singletonObjects中。MapperFactoryBean實現了FactoryBean介面,在獲取Mapper介面的時候,預設返回的是MapperFactoryBean的getObject()方法,其中具體返回xxxMapper介面的動態代理類(JDK代理方式)。動態代理類會進行快取。

原理

​ 通過配置@MapperScan(basePackages = {"com.ybe.mapper"}) 註解,向 BeanDefinitionRegistry 中新增型別為 MapperScannerConfigurer 的BeanDefinition物件並且初始化物件相關屬性,在org.springframework.context.support.AbstractApplicationContext#invokeBeanFactoryPostProcessors 中會進行呼叫MapperScannerConfigurer 的postProcessBeanDefinitionRegistry 方法,該方法會掃描配置的包路徑下的Mapper介面class檔案,生成BeanClass為MapperFactoryBean的ScannedGenericBeanDefinition,註冊到 BeanDefinitionRegistry 中。

原始碼解析

  1. @MapperScan註解原始碼如下
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MapperScannerRegistrar.class)
@Repeatable(MapperScans.class)
  1. 在 org.springframework.context.support.AbstractApplicationContext#invokeBeanFactoryPostProcessors 方法中,會先執行 org.springframework.context.annotation.ConfigurationClassPostProcessor#processConfigBeanDefinitions的方法,其中會執行MapperScannerRegistrar類的registerBeanDefinitions方法,向 BeanDefinitionRegistry 註冊了一個型別為 MapperScannerConfigurer的BeanDefinition物件。程式碼如下,
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
  1. MapperScannerConfigurer實現了BeanDefinitionRegistryPostProcessor介面。MapperScannerConfigurer主要用來掃描具體的 Mapper介面class檔案,生成BeanClass型別為MapperFactoryBean的ScannedGenericBeanDefinition物件後注入 BeanDefinitionRegistry 中。具體類圖如下

  2. 在org.springframework.context.support.AbstractApplicationContext#invokeBeanFactoryPostProcessors中會接著執行,MapperScannerConfigurer的postProcessBeanDefinitionRegistry 方法。postProcessBeanDefinitionRegistry中大概邏輯為

搜尋指定包下面的Mapper介面,

// 開始搜尋 basePackage
scanner.scan(
    StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));

生成ScannedGenericBeanDefinition,並以Mapper介面名稱為BeanName注入到BeanDefinitionRegistry物件中。

BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
definitionHolder =
    AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
registerBeanDefinition(definitionHolder, this.registry);

然後再設定ScannedGenericBeanDefinition的BeanClass型別為MapperFactoryBean類。 關鍵程式碼程式碼如下

// 設定 definition 的  建構函式的引數值型別為 beanClassName,
// 在建立 MapperFactoryBean 時,會根據beanClassName建立類,然後把類作為引數呼叫MapperFactoryBean帶引數的構造方法
definition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName); // issue #59
// 設定 definition 的  Bean 型別為 MapperFactoryBean.class
definition.setBeanClass(this.mapperFactoryBeanClass);
  1. 每個Mapper介面檔案對應的BeanDefinition為 ScannedGenericBeanDefinition,BeanDefinition的BeanClass實現類為 MapperFactoryBean 類。此時檢視beanFactory的 beanDefinitionMap 中的值,如下圖

  2. MapperFactoryBean是一個泛型類,泛型用來表示不同介面型別。繼承了SqlSessionDaoSupport類,該類中儲存了Maybatis的SqlSession工廠類。MapperFactoryBean也是一個實現了FactoryBean 的類,用來返回具體的型別以及根據型別來生成具體的Mapper介面代理類。

@Override
public T getObject() throws Exception {
    // 返回根據介面型別返回 SqlSession中的Mapper代理物件
    return getSqlSession().getMapper(this.mapperInterface);
}

/**
   * {@inheritDoc}
   */
@Override
public Class<T> getObjectType() {
    return this.mapperInterface;
}
  1. 在beanFactory.preInstantiateSingletons()方法中會把BeanDefinition生成具體的Bean物件,在建立 MapperFactoryBean 物件的時候會呼叫帶引數的構造方法(上面有具體說明)。因為在配置類中我們注入了SqlSessionFactoryBean物件(具體解析過程在下面章節講解),SqlSessionFactoryBean物件實現了FactoryBean 介面,在Srping容器中會返回SqlSessionFactory型別物件。在給MapperFactoryBean屬性賦值的時候會把SqlSessionFactoryBean的實際SqlSessionFactory物件賦值給sqlSessionTemplate屬性。最終會在beanFactory.singletonObjects物件中新增以Mapper介面名稱為key,以 MapperFactoryBean 型別為value的 記錄。

  2. 在獲取Mapper介面的Bean物件的時候,會呼叫getObject()方法,其中會調SqlSessionTemplate的getMapper(),程式碼如下

@Override
public <T> T getMapper(Class<T> type) {
  return getConfiguration().getMapper(type, this);
}
  1. 以上呼叫Configuration的getMapper()方法,configuration就是Mybatis的類了。程式碼如下,
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    // 根據Mapper介面型別獲取已經註冊的物件
    return mapperRegistry.getMapper(type, sqlSession);
}
  1. 返回建立的動態代理物件,這裡返回的動態代理物件之後不會更新beanFactory.singletonObjects的物件,並且會進行快取處理。關鍵程式碼如下
@SuppressWarnings("unchecked")
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
  // 根據 Mapper 介面型別獲取已經註冊的物件
  final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
  if (mapperProxyFactory == null) {
    throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
  }
  try {
    // 建立動態代理物件
    return mapperProxyFactory.newInstance(sqlSession);
  } catch (Exception e) {
    throw new BindingException("Error getting mapper instance. Cause: " + e, e);
  }
}
  1. 總結一下,beanFactory.singletonObjects關於Mapper介面儲存的Bean物件是泛型的MapperFactoryBean物件。但是根據Mapper介面獲取Bean物件會返回上面的動態代理物件,並且動態代理物件會快取在beanFactory.factoryBeanObjectCache中,這是因為MapperFactoryBean實現的FactoryBean 介面。

2.1 SqlSessionFactoryBean 注入

SqlSessionFactoryBean介紹

通過@Bean方式可以將SqlSessionFactoryBean物件注入到Spring容器,SqlSessionFactoryBean物件在MapperFactoryBean物件中會用到。注入程式碼如下,

@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws IOException {
    // 建立 SqlSessionFactoryBean 的類
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    // 設定資料來源
    factoryBean.setDataSource(dataSource);
    // 設定配置檔案路徑
    factoryBean.setConfigLocation(new ClassPathResource("mybatis.xml"));
    // 設定 mybaits.xml 檔案
    factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                                   .getResources("classpath:com/ybe/mapper/*.xml"));
    // 設定別名
    factoryBean.setTypeAliases(Book.class);
    return factoryBean;
}

SqlSessionFactoryBean的類繼承關係圖如下,

SqlSessionFactoryBean實現了InitializingBean介面 ,會在初始化後會執行afterPropertiesSet方法,其中會呼叫buildSqlSessionFactory()方法進行SqlSessionFactory的建立。SqlSessionFactoryBean也實現了FactoryBean 介面,在容器中如果獲取SqlSessionFactoryBean物件會返回SqlSessionFactory物件,並且也會在beanFactory.factoryBeanObjectCache進行快取。getObject原始碼如下,

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

  return this.sqlSessionFactory;
}

buildSqlSessionFactory()具體邏輯

​ 1. 根據 configLocation 建立 XMLConfigBuilder 以及 Configuration物件

xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
targetConfiguration = xmlConfigBuilder.getConfiguration();

​ 2. 讀取SqlSessionFactoryBean的屬性物件給 targetConfiguration 賦值

Optional.ofNullable(this.objectFactory).ifPresent(targetConfiguration::setObjectFactory);
Optional.ofNullable(this.objectWrapperFactory).ifPresent(targetConfiguration::setObjectWrapperFactory);
Optional.ofNullable(this.vfs).ifPresent(targetConfiguration::setVfsImpl);

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

​ 3. 解析主配置檔案

xmlConfigBuilder.parse();

​ 4. targetConfiguration設定環境變數,如果配置的transactionFactory 事務工廠類為 null,則建立 SpringManagedTransactionFactory 事務工廠類,該事務工廠會直接呼叫org.springframework.jdbc.datasource.DataSourceUtils去獲取資料庫連線物件,所以和Spring的事務進行了整合。程式碼如下,

// 設定環境變數,如果事務工程類為 null,則建立 SpringManagedTransactionFactory 事務工廠類
targetConfiguration.setEnvironment(new Environment(this.environment,
this.transactionFactory == null ? new SpringManagedTransactionFactory() : this.transactionFactory,
this.dataSource));

​ 5. 如果 mapperLocations 不為null ,則迴圈遍歷 xxxMapper.xml 檔案流,解析之後給 targetConfiguration 的相關物件賦值。程式碼如下,

for (Resource mapperLocation : this.mapperLocations) {
    if (mapperLocation == null) {
        continue;
    }
    try {
        // 構建 XMLMapperBuilder 物件,進行mapper.xml 檔案資源解析
        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. 總結一下,整個過程比較簡單,其主要就是Mybaits初始化的過程,更詳細Mybatis初始化過程請參考上一篇文章。