1. 程式人生 > 其它 >Mybatis原始碼-SqlSession(二)

Mybatis原始碼-SqlSession(二)

1、例項程式碼
在例項搭建文章中,通過 SqlSession 物件查詢資料,可樂寫了兩種方法。
①、常規的需要我們拼接 statement 方式;
②、xxxMapper.interface 介面代理方式;

對應下面兩種方法:

//根據id查詢person表資料
@Test
public void testSelectPersonById() {
    /*這個字串由 PersonMapper.xml 檔案中 兩個部分構成
        <mapper namespace="com.itcoke.mapper.PersonMapper"> 的 namespace 的值
        <select id="selectPersonById" > id 值
    
*/ String namespace = "com.itcoke.mapper.PersonMapper"; String method = "selectPersonById"; //根據 sqlSessionFactory 產生 session SqlSession sqlSession = sessionFactory.openSession(); Person person = sqlSession.selectOne(namespace + "." + method, 1L); System.out.println(person); sqlSession.close(); }
//根據id查詢person表資料 //通過介面代理的方式 @Test public void testInterfaceSelectPersonById() { //根據 sqlSessionFactory 產生 session SqlSession sqlSession = sessionFactory.openSession(); PersonMapper mapper = sqlSession.getMapper(PersonMapper.class); Person person = mapper.selectPersonById(1L); System.out.println(person); sqlSession.close(); }

2、構建過程圖示

3、程式碼剖析
3.1 Executor
我們通過 DefaultSessionFactory.openSession() 方法獲取 sqlSession

public interface SqlSessionFactory {
  
    SqlSession openSession();
  
    SqlSession openSession(boolean autoCommit);
  
    SqlSession openSession(Connection connection);
  
    SqlSession openSession(TransactionIsolationLevel level);
  
    SqlSession openSession(ExecutorType execType);
  
    SqlSession openSession(ExecutorType execType, boolean autoCommit);
  
    SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
  
    SqlSession openSession(ExecutorType execType, Connection connection);
  
    Configuration getConfiguration();
  
  }

其實是可以通過構造方法指定 Executor 的型別,比如:

SqlSession sqlSession = sessionFactory.openSession(ExecutorType.SIMPLE);

再看生成 Executor 的原始碼:在Configuration類中

  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    if (ExecutorType.BATCH == executorType) {
      executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
      executor = new ReuseExecutor(this, transaction);
    } else {
      executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

如果不指定執行器型別,直接預設 openSession() 方法,生成的是 CachingExecutor 執行器,這裡的 cacheEnabled 其實是預設開啟二級快取的配置,在 mybatis-config.xml 檔案中.
並且需要注意的是這裡 new CachingExecutor(executor),傳進去了一個 SimpleExecutor 物件,後面和資料庫互動的實際上是該物件。





    郭慕榮部落格園