spring-mybatis源碼解析

SqlSessionFactoryBuilder

SqlSessionFactory->SqlSessionFactoryBuilder.build(Configuration)

SqlSession->SqlSessionFactory.openSession()

Mapper ->SqlSession.getMapper()

Executor

mybatis啓動過程
創建配置文件的時候,會去讀取配置的所有信息。
XMLConfigBuilder讀取到package標籤的時候,獲取該標籤配置包下的所有接口(這裏就是我們對應的mapper接口),在configuration中添加了MapperRegister,這個對象中保存的Map<Class<?>, MapperProxyFactory<?>> ,key就是接口路徑,value就是mapper接口的代理對象。 在我們調用session.getMapper的時候就會返回該代理對象的實例。

public class MapperRegistry {
    private final Configuration config;
    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap();

spring整合mybatis :

spring-mybatis

  1. sqlSessionFactoryBean 加載configuration配置,同時註冊 sqlSessionFactory
  2. 註解的mapper bean,其實他的beanClass被改寫成了MapperFactoryBean,在初始化的時候會調用,他的getObject的方法,這個方法最後獲取的就是原來mybatis的mapper接口的代理對象。

在我們使用註解的bean去調用方法時,這個bean其實是個代理bean。也就是 MapperFactoryBean,
MapperFactoryBean<T> extends SqlSessionDaoSupport 
(SqlSessionDaoSupport 中可以獲取sqlSessionTemplate)

  public T getObject() throws Exception {
    return getSqlSession().getMapper(this.mapperInterface);
  }

 public <T> T getMapper(Class<T> type) {
    return getConfiguration().getMapper(type, this);
  }
  //這裏mapperRegistry中就是原來mybatis中保存的具體每個mapper 接口的代理對象
 public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        return this.mapperRegistry.getMapper(type, sqlSession);
    } 

使用這個bean會調用,getObject()方法,其中getSqlSession()返回sqlSessionTemplate
在這個template中會通過set方法注入 sqlSessionFactory,
然後template通過sqlSessionFactory就可以獲取配置信息,拿到每個mapper的代理對象(mybatis中的代理對象)

然後這個代理的MapperFactoryBean也就是最終的mapper的代理對象了。
最終的sql交由template中sqlSessionProxy對象去處理,這裏面,做了事務的處理,是對DefaultSqlSession的包裝(因爲這裏DefaultSqlSession是線程不安全的)
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章