天天看點

深入了解mybatis

MyBatis是目前非常流行的ORM架構,它的功能很強大,然而其實作卻比較簡單、優雅。本文主要講述MyBatis的架構設計思路,并且讨論MyBatis的幾個核心部件,然後結合一個select查詢執行個體,深入代碼,來探究MyBatis的實作。

一、MyBatis的架構設計

        注:上圖很大程度上參考了iteye 上的chenjc_it   所寫的博文原理分析之二:架構整體設計 中的MyBatis架構體圖,chenjc_it總結的非常好,贊一個!

1.接口層---和資料庫互動的方式

MyBatis和資料庫的互動有兩種方式:

a.使用傳統的MyBatis提供的API;

b. 使用Mapper接口

    1.1.使用傳統的MyBatis提供的API
      這是傳統的傳遞Statement Id 和查詢參數給 SqlSession 對象,使用 SqlSession對象完成和資料庫的互動;MyBatis 提供了非常友善和簡單的API,供使用者實作對資料庫的增删改查資料操作,以及對資料庫連接配接資訊和MyBatis 自身配置資訊的維護操作。
      上述使用MyBatis 的方法,是建立一個和資料庫打交道的SqlSession對象,然後根據Statement Id 和參數來操作資料庫,這種方式固然很簡單和實用,但是它不符合面向對象語言的概念和面向接口程式設計的程式設計習慣。由于面向接口的程式設計是面向對象的大趨勢,MyBatis 為了适應這一趨勢,增加了第二種使用MyBatis 支援接口(Interface)調用方式。
1.2. 使用Mapper接口
 MyBatis 将配置檔案中的每一個<mapper> 節點抽象為一個 Mapper 接口,而這個接口中聲明的方法和跟<mapper> 節點中的<select|update|delete|insert> 節點項對應,即<select|update|delete|insert> 節點的id值為Mapper 接口中的方法名稱,parameterType 值表示Mapper 對應方法的入參類型,而resultMap 值則對應了Mapper 接口表示的傳回值類型或者傳回結果集的元素類型。

 根據MyBatis 的配置規範配置好後,通過SqlSession.getMapper(XXXMapper.class) 方法,MyBatis 會根據相應的接口聲明的方法資訊,通過動态代理機制生成一個Mapper 執行個體,我們使用Mapper 接口的某一個方法時,MyBatis 會根據這個方法的方法名和參數類型,确定Statement Id,底層還是通過SqlSession.select("statementId",parameterObject);或者SqlSession.update("statementId",parameterObject); 等等來實作對資料庫的操作,(至于這裡的動态機制是怎樣實作的,我将準備專門一片文章來讨論,敬請關注~)

MyBatis 引用Mapper 接口這種調用方式,純粹是為了滿足面向接口程式設計的需要。(其實還有一個原因是在于,面向接口的程式設計,使得使用者在接口上可以使用注解來配置SQL語句,這樣就可以脫離XML配置檔案,實作“0配置”)。

2.資料處理層

      資料處理層可以說是MyBatis 的核心,從大的方面上講,它要完成三個功能:

a. 通過傳入參數建構動态SQL語句;

b. SQL語句的執行以及封裝查詢結果內建List<E>

     2.1.參數映射和動态SQL語句生成

       動态語句生成可以說是MyBatis架構非常優雅的一個設計,MyBatis 通過傳入的參數值,使用 Ognl 來動态地構造SQL語句,使得MyBatis 有很強的靈活性和擴充性。

參數映射指的是對于Java 資料類型和jdbc資料類型之間的轉換:這裡有包括兩個過程:查詢階段,我們要将java類型的資料,轉換成jdbc類型的資料,通過 preparedStatement.setXXX() 來設值;另一個就是對resultset查詢結果集的jdbcType 資料轉換成java 資料類型。

(至于具體的MyBatis是如何動态建構SQL語句的,我将準備專門一篇文章來讨論,敬請關注~)

     2.2. SQL語句的執行以及封裝查詢結果內建List<E>

              動态SQL語句生成之後,MyBatis 将執行SQL語句,并将可能傳回的結果集轉換成List<E> 清單。MyBatis 在對結果集的進行中,支援結果集關系一對多和多對一的轉換,并且有兩種支援方式,一種為嵌套查詢語句的查詢,還有一種是嵌套結果集的查詢。

3. 架構支撐層

     3.1. 事務管理機制
          事務管理機制對于ORM架構而言是不可缺少的一部分,事務管理機制的品質也是考量一個ORM架構是否優秀的一個标準,對于資料管理機制我已經在我的博文《深入了解mybatis原理》 MyBatis事務管理機制 中有非常詳細的讨論,感興趣的讀者可以點選檢視。
    3.2. 連接配接池管理機制
由于建立一個資料庫連接配接所占用的資源比較大, 對于資料吞吐量大和通路量非常大的應用而言,連接配接池的設計就顯得非常重要,對于連接配接池管理機制我已經在我的博文《深入了解mybatis原理》 Mybatis資料源與連接配接池 中有非常詳細的讨論,感興趣的讀者可以點選檢視。
   3.3. 緩存機制
為了提高資料使用率和減小伺服器和資料庫的壓力,MyBatis 會對于一些查詢提供會話級别的資料緩存,會将對某一次查詢,放置到SqlSession中,在允許的時間間隔内,對于完全相同的查詢,MyBatis 會直接将緩存結果傳回給使用者,而不用再到資料庫中查找。(至于具體的MyBatis緩存機制,我将準備專門一篇文章來讨論,敬請關注~)
  3. 4. SQL語句的配置方式
傳統的MyBatis 配置SQL 語句方式就是使用XML檔案進行配置的,但是這種方式不能很好地支援面向接口程式設計的理念,為了支援面向接口的程式設計,MyBatis 引入了Mapper接口的概念,面向接口的引入,對使用注解來配置SQL 語句成為可能,使用者隻需要在接口上添加必要的注解即可,不用再去配置XML檔案了,但是,目前的MyBatis 隻是對注解配置SQL 語句提供了有限的支援,某些進階功能還是要依賴XML配置檔案配置SQL 語句。

4 引導層

引導層是配置和啟動MyBatis 配置資訊的方式。MyBatis 提供兩種方式來引導MyBatis :基于XML配置檔案的方式和基于Java API 的方式,讀者可以參考我的另一片博文:Java Persistence with MyBatis 3(中文版) 第二章 引導MyBatis

二、MyBatis的主要構件及其互相關系

  從MyBatis代碼實作的角度來看,MyBatis的主要的核心部件有以下幾個:

  • SqlSession            作為MyBatis工作的主要頂層API,表示和資料庫互動的會話,完成必要資料庫增删改查功能
  • Executor              MyBatis執行器,是MyBatis 排程的核心,負責SQL語句的生成和查詢緩存的維護
  • StatementHandler   封裝了JDBC Statement操作,負責對JDBC statement 的操作,如設定參數、将Statement結果集轉換成List集合。
  • ParameterHandler   負責對使用者傳遞的參數轉換成JDBC Statement 所需要的參數,
  • ResultSetHandler    負責将JDBC傳回的ResultSet結果集對象轉換成List類型的集合;
  • TypeHandler          負責java資料類型和jdbc資料類型之間的映射和轉換
  • MappedStatement   MappedStatement維護了一條<select|update|delete|insert>節點的封裝, 
  • SqlSource            負責根據使用者傳遞的parameterObject,動态地生成SQL語句,将資訊封裝到BoundSql對象中,并傳回
  • BoundSql             表示動态生成的SQL語句以及相應的參數資訊
  • Configuration        MyBatis所有的配置資訊都維持在Configuration對象之中。

(注:這裡隻是列出了我個人認為屬于核心的部件,請讀者不要先入為主,認為MyBatis就隻有這些部件哦!每個人對MyBatis的了解不同,分析出的結果自然會有所不同,歡迎讀者提出質疑和不同的意見,我們共同探讨~)

它們的關系如下圖所示:

三、從MyBatis一次select 查詢語句來分析MyBatis的架構設計

一、資料準備(非常熟悉和應用過MyBatis 的讀者可以迅速浏覽此節即可)

     1. 準備資料庫資料,建立EMPLOYEES表,插入資料:      

[sql] view plain copy

 print?

  1.   --建立一個員工基本資訊表  
  2.    create  table "EMPLOYEES"(  
  3.        "EMPLOYEE_ID" NUMBER(6) not null,  
  4.       "FIRST_NAME" VARCHAR2(20),  
  5.       "LAST_NAME" VARCHAR2(25) not null,  
  6.       "EMAIL" VARCHAR2(25) not null unique,  
  7.       "SALARY" NUMBER(8,2),  
  8.        constraint "EMP_EMP_ID_PK" primary key ("EMPLOYEE_ID")  
  9.    );  
  10.    comment on table EMPLOYEES is '員工資訊表';  
  11.    comment on column EMPLOYEES.EMPLOYEE_ID is '員工id';  
  12.    comment on column EMPLOYEES.FIRST_NAME is 'first name';  
  13.    comment on column EMPLOYEES.LAST_NAME is 'last name';  
  14.    comment on column EMPLOYEES.EMAIL is 'email address';  
  15.    comment on column EMPLOYEES.SALARY is 'salary';  
  16.    --添加資料  
  17. insert into EMPLOYEES (EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, SALARY)  
  18. values (100, 'Steven', 'King', 'SKING', 24000.00);  
  19. values (101, 'Neena', 'Kochhar', 'NKOCHHAR', 17000.00);  
  20. values (102, 'Lex', 'De Haan', 'LDEHAAN', 17000.00);  
  21. values (103, 'Alexander', 'Hunold', 'AHUNOLD', 9000.00);  
  22. values (104, 'Bruce', 'Ernst', 'BERNST', 6000.00);  
  23. values (105, 'David', 'Austin', 'DAUSTIN', 4800.00);  
  24. values (106, 'Valli', 'Pataballa', 'VPATABAL', 4800.00);  
  25. values (107, 'Diana', 'Lorentz', 'DLORENTZ', 4200.00);      
  2. 配置Mybatis的配置檔案,命名為mybatisConfig.xml:
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  4. <configuration>  
  5.   <environments default="development">  
  6.     <environment id="development">  
  7.       <transactionManager type="JDBC" />  
  8.       <dataSource type="POOLED">  
  9.      <property name="driver" value="oracle.jdbc.driver.OracleDriver" />    
  10.          <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />    
  11.          <property name="username" value="louis" />    
  12.          <property name="password" value="123456" />  
  13.       </dataSource>  
  14.     </environment>  
  15.   </environments>  
  16.     <mappers>  
  17.        <mapper  resource="com/louis/mybatis/domain/EmployeesMapper.xml"/>  
  18.     </mappers>  
  19. </configuration>  
3.     建立Employee實體Bean 以及配置Mapper配置檔案
[java] view plain copy
  1. package com.louis.mybatis.model;  
  2. import java.math.BigDecimal;  
  3. public class Employee {  
  4.     private Integer employeeId;  
  5.     private String firstName;  
  6.     private String lastName;  
  7.     private String email;  
  8.     private BigDecimal salary;  
  9.     public Integer getEmployeeId() {  
  10.         return employeeId;  
  11.     }  
  12.     public void setEmployeeId(Integer employeeId) {  
  13.         this.employeeId = employeeId;  
  14.     public String getFirstName() {  
  15.         return firstName;  
  16.     public void setFirstName(String firstName) {  
  17.         this.firstName = firstName;  
  18.     public String getLastName() {  
  19.         return lastName;  
  20.     public void setLastName(String lastName) {  
  21.         this.lastName = lastName;  
  22.     public String getEmail() {  
  23.         return email;  
  24.     public void setEmail(String email) {  
  25.         this.email = email;  
  26.     public BigDecimal getSalary() {  
  27.         return salary;  
  28.     public void setSalary(BigDecimal salary) {  
  29.         this.salary = salary;  
  30. }  
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  
  3. <mapper namespace="com.louis.mybatis.dao.EmployeesMapper" >  
  4.   <resultMap id="BaseResultMap" type="com.louis.mybatis.model.Employee" >  
  5.     <id column="EMPLOYEE_ID" property="employeeId" jdbcType="DECIMAL" />  
  6.     <result column="FIRST_NAME" property="firstName" jdbcType="VARCHAR" />  
  7.     <result column="LAST_NAME" property="lastName" jdbcType="VARCHAR" />  
  8.     <result column="EMAIL" property="email" jdbcType="VARCHAR" />  
  9.     <result column="SALARY" property="salary" jdbcType="DECIMAL" />  
  10.   </resultMap>  
  11.   <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >  
  12.     select   
  13.         EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, SALARY  
  14.         from LOUIS.EMPLOYEES  
  15.         where EMPLOYEE_ID = #{employeeId,jdbcType=DECIMAL}  
  16.   </select>  
  17. </mapper>  
4. 建立eclipse 或者myeclipse 的maven項目,maven配置如下:
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  3.   <modelVersion>4.0.0</modelVersion>  
  4.   <groupId>batis</groupId>  
  5.   <artifactId>batis</artifactId>  
  6.   <version>0.0.1-SNAPSHOT</version>  
  7.   <packaging>jar</packaging>  
  8.   <name>batis</name>  
  9.   <url>http://maven.apache.org</url>  
  10.   <properties>  
  11.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  12.   </properties>  
  13.   <dependencies>  
  14.     <dependency>  
  15.       <groupId>junit</groupId>  
  16.       <artifactId>junit</artifactId>  
  17.       <version>3.8.1</version>  
  18.       <scope>test</scope>  
  19.     </dependency>  
  20.             <groupId>org.mybatis</groupId>  
  21.             <artifactId>mybatis</artifactId>  
  22.             <version>3.2.7</version>  
  23.         <groupId>com.oracle</groupId>  
  24.         <artifactId>ojdbc14</artifactId>  
  25.         <version>10.2.0.4.0</version>  
  26.   </dependencies>  
  27. </project>  
 5. 用戶端代碼:
  1. package com.louis.mybatis.test;  
  2. import java.io.InputStream;  
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import org.apache.ibatis.io.Resources;  
  7. import org.apache.ibatis.session.SqlSession;  
  8. import org.apache.ibatis.session.SqlSessionFactory;  
  9. import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
  10. import com.louis.mybatis.model.Employee;  
  11. /** 
  12.  * SqlSession 簡單查詢示範類 
  13.  * @author louluan 
  14.  */  
  15. public class SelectDemo {  
  16.     public static void main(String[] args) throws Exception {  
  17.         /* 
  18.          * 1.加載mybatis的配置檔案,初始化mybatis,建立出SqlSessionFactory,是建立SqlSession的工廠 
  19.          * 這裡隻是為了示範的需要,SqlSessionFactory臨時建立出來,在實際的使用中,SqlSessionFactory隻需要建立一次,當作單例來使用 
  20.          */  
  21.         InputStream inputStream = Resources.getResourceAsStream("mybatisConfig.xml");  
  22.         SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();  
  23.         SqlSessionFactory factory = builder.build(inputStream);  
  24.         //2. 從SqlSession工廠 SqlSessionFactory中建立一個SqlSession,進行資料庫操作  
  25.         SqlSession sqlSession = factory.openSession();  
  26.         //3.使用SqlSession查詢  
  27.         Map<String,Object> params = new HashMap<String,Object>();  
  28.         params.put("min_salary",10000);  
  29.         //a.查詢工資低于10000的員工  
  30.         List<Employee> result = sqlSession.selectList("com.louis.mybatis.dao.EmployeesMapper.selectByMinSalary",params);  
  31.         //b.未傳最低工資,查所有員工  
  32.         List<Employee> result1 = sqlSession.selectList("com.louis.mybatis.dao.EmployeesMapper.selectByMinSalary");  
  33.         System.out.println("薪資低于10000的員工數:"+result.size());  
  34.         //~output :   查詢到的資料總數:5    
  35.         System.out.println("所有員工數: "+result1.size());  
  36.         //~output :  所有員工數: 8  

二、SqlSession 的工作過程分析:

 1. 開啟一個資料庫通路會話---建立SqlSession對象:

  1. SqlSession sqlSession = factory.openSession();  

           MyBatis封裝了對資料庫的通路,把對資料庫的會話和事務控制放到了SqlSession對象中。

2. 為SqlSession傳遞一個配置的Sql語句 的Statement Id和參數,然後傳回結果:

  1. List<Employee> result = sqlSession.selectList("com.louis.mybatis.dao.EmployeesMapper.selectByMinSalary",params);  

上述的"com.louis.mybatis.dao.EmployeesMapper.selectByMinSalary",是配置在EmployeesMapper.xml 的Statement ID,params 是傳遞的查詢參數。

讓我們來看一下sqlSession.selectList()方法的定義: 

  1. public <E> List<E> selectList(String statement, Object parameter) {  
  2.   return this.selectList(statement, parameter, RowBounds.DEFAULT);  
  3. public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {  
  4.   try {  
  5.     //1.根據Statement Id,在mybatis 配置對象Configuration中查找和配置檔案相對應的MappedStatement      
  6.     MappedStatement ms = configuration.getMappedStatement(statement);  
  7.     //2. 将查詢任務委托給MyBatis 的執行器 Executor  
  8.     List<E> result = executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);  
  9.     return result;  
  10.   } catch (Exception e) {  
  11.     throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);  
  12.   } finally {  
  13.     ErrorContext.instance().reset();  
  14.   }  
MyBatis在初始化的時候,會将MyBatis的配置資訊全部加載到記憶體中,使用org.apache.ibatis.session.Configuration執行個體來維護。使用者可以使用sqlSession.getConfiguration()方法來擷取。MyBatis的配置檔案中配置資訊的組織格式和記憶體中對象的組織格式幾乎完全對應的。上述例子中的
  1. <select id="selectByMinSalary" resultMap="BaseResultMap" parameterType="java.util.Map" >  
  2.   select   
  3.     EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, SALARY  
  4.     from LOUIS.EMPLOYEES  
  5.     <if test="min_salary != null">  
  6.         where SALARY < #{min_salary,jdbcType=DECIMAL}  
  7.     </if>  
  8. </select>  

加載到記憶體中會生成一個對應的MappedStatement對象,然後會以key="com.louis.mybatis.dao.EmployeesMapper.selectByMinSalary" ,value為MappedStatement對象的形式維護到Configuration的一個Map中。當以後需要使用的時候,隻需要通過Id值來擷取就可以了。

從上述的代碼中我們可以看到SqlSession的職能是:

SqlSession根據Statement ID, 在mybatis配置對象Configuration中擷取到對應的MappedStatement對象,然後調用mybatis執行器來執行具體的操作。

3.MyBatis執行器Executor根據SqlSession傳遞的參數執行query()方法(由于代碼過長,讀者隻需閱讀我注釋的地方即可):

  1. * BaseExecutor 類部分代碼 
  2. */  
  3. public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {  
  4.     // 1.根據具體傳入的參數,動态地生成需要執行的SQL語句,用BoundSql對象表示    
  5.     BoundSql boundSql = ms.getBoundSql(parameter);  
  6.     // 2.為目前的查詢建立一個緩存Key  
  7.     CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);  
  8.     return query(ms, parameter, rowBounds, resultHandler, key, boundSql);  
  9.  }  
  10.   @SuppressWarnings("unchecked")  
  11.   public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {  
  12.     ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());  
  13.     if (closed) throw new ExecutorException("Executor was closed.");  
  14.     if (queryStack == 0 && ms.isFlushCacheRequired()) {  
  15.       clearLocalCache();  
  16.     List<E> list;  
  17.     try {  
  18.       queryStack++;  
  19.       list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;  
  20.       if (list != null) {  
  21.         handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);  
  22.       } else {  
  23.         // 3.緩存中沒有值,直接從資料庫中讀取資料    
  24.         list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);  
  25.       }  
  26.     } finally {  
  27.       queryStack--;  
  28.     if (queryStack == 0) {  
  29.       for (DeferredLoad deferredLoad : deferredLoads) {  
  30.         deferredLoad.load();  
  31.       deferredLoads.clear(); // issue #601  
  32.       if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {  
  33.         clearLocalCache(); // issue #482  
  34.     return list;  
  35.  private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {  
  36.     localCache.putObject(key, EXECUTION_PLACEHOLDER);  
  37.       //4. 執行查詢,傳回List 結果,然後    将查詢的結果放入緩存之中  
  38.       list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);  
  39.       localCache.removeObject(key);  
  40.     localCache.putObject(key, list);  
  41.     if (ms.getStatementType() == StatementType.CALLABLE) {  
  42.       localOutputParameterCache.putObject(key, parameter);  
  1. *SimpleExecutor類的doQuery()方法實作 
  2.   public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {  
  3.     Statement stmt = null;  
  4.       Configuration configuration = ms.getConfiguration();  
  5.       //5. 根據既有的參數,建立StatementHandler對象來執行查詢操作  
  6.       StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);  
  7.       //6. 建立java.Sql.Statement對象,傳遞給StatementHandler對象  
  8.       stmt = prepareStatement(handler, ms.getStatementLog());  
  9.       //7. 調用StatementHandler.query()方法,傳回List結果集  
  10.       return handler.<E>query(stmt, resultHandler);  
  11.       closeStatement(stmt);  

上述的Executor.query()方法幾經轉折,最後會建立一個StatementHandler對象,然後将必要的參數傳遞給StatementHandler,使用StatementHandler來完成對資料庫的查詢,最終傳回List結果集。

從上面的代碼中我們可以看出,Executor的功能和作用是:

(1、根據傳遞的參數,完成SQL語句的動态解析,生成BoundSql對象,供StatementHandler使用;

(2、為查詢建立緩存,以提高性能(具體它的緩存機制不是本文的重點,我會單獨拿出來跟大家探讨,感興趣的讀者可以關注我的其他博文);

(3、建立JDBC的Statement連接配接對象,傳遞給StatementHandler對象,傳回List查詢結果。

4. StatementHandler對象負責設定Statement對象中的查詢參數、處理JDBC傳回的resultSet,将resultSet加工為List 集合傳回:

      接着上面的Executor第六步,看一下:prepareStatement() 方法的實作:
  1. public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException { Statement stmt = null; try { Configuration configuration = ms.getConfiguration(); StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql); // 1.準備Statement對象,并設定Statement對象的參數 stmt = prepareStatement(handler, ms.getStatementLog()); // 2. StatementHandler執行query()方法,傳回List結果 return handler.<E>query(stmt, resultHandler); } finally { closeStatement(stmt); } }  
  2.   private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {  
  3.     Statement stmt;  
  4.     Connection connection = getConnection(statementLog);  
  5.     stmt = handler.prepare(connection);  
  6.     //對建立的Statement對象設定參數,即設定SQL 語句中 ? 設定為指定的參數  
  7.     handler.parameterize(stmt);  
  8.     return stmt;  

      以上我們可以總結StatementHandler對象主要完成兩個工作:

         (1. 對于JDBC的PreparedStatement類型的對象,建立的過程中,我們使用的是SQL語句字元串會包含 若幹個? 占位符,我們其後再對占位符進行設值。

StatementHandler通過parameterize(statement)方法對Statement進行設值;       

         (2.StatementHandler通過List<E> query(Statement statement, ResultHandler resultHandler)方法來完成執行Statement,和将Statement對象傳回的resultSet封裝成List;

5.   StatementHandler 的parameterize(statement) 方法的實作:

  1. *   StatementHandler 類的parameterize(statement) 方法實作  
  2. public void parameterize(Statement statement) throws SQLException {  
  3.     //使用ParameterHandler對象來完成對Statement的設值    
  4.     parameterHandler.setParameters((PreparedStatement) statement);  
  1.  *  
  2.  *ParameterHandler類的setParameters(PreparedStatement ps) 實作 
  3.  * 對某一個Statement進行設定參數 
  4. public void setParameters(PreparedStatement ps) throws SQLException {  
  5.   ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());  
  6.   List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();  
  7.   if (parameterMappings != null) {  
  8.     for (int i = 0; i < parameterMappings.size(); i++) {  
  9.       ParameterMapping parameterMapping = parameterMappings.get(i);  
  10.       if (parameterMapping.getMode() != ParameterMode.OUT) {  
  11.         Object value;  
  12.         String propertyName = parameterMapping.getProperty();  
  13.         if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params  
  14.           value = boundSql.getAdditionalParameter(propertyName);  
  15.         } else if (parameterObject == null) {  
  16.           value = null;  
  17.         } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {  
  18.           value = parameterObject;  
  19.         } else {  
  20.           MetaObject metaObject = configuration.newMetaObject(parameterObject);  
  21.           value = metaObject.getValue(propertyName);  
  22.         }  
  23.         // 每一個Mapping都有一個TypeHandler,根據TypeHandler來對preparedStatement進行設定參數  
  24.         TypeHandler typeHandler = parameterMapping.getTypeHandler();  
  25.         JdbcType jdbcType = parameterMapping.getJdbcType();  
  26.         if (value == null && jdbcType == null) jdbcType = configuration.getJdbcTypeForNull();  
  27.         // 設定參數  
  28.         typeHandler.setParameter(ps, i + 1, value, jdbcType);  

從上述的代碼可以看到,StatementHandler 的parameterize(Statement) 方法調用了 ParameterHandler的setParameters(statement) 方法,

ParameterHandler的setParameters(Statement)方法負責 根據我們輸入的參數,對statement對象的 ? 占位符處進行指派。

6.   StatementHandler 的List<E> query(Statement statement, ResultHandler resultHandler)方法的實作:

  1.  /** 
  2.   * PreParedStatement類的query方法實作 
  3.   */  
  4.  public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {  
  5. // 1.調用preparedStatemnt。execute()方法,然後将resultSet交給ResultSetHandler處理    
  6.    PreparedStatement ps = (PreparedStatement) statement;  
  7.    ps.execute();  
  8.    //2. 使用ResultHandler來處理ResultSet  
  9.    return resultSetHandler.<E> handleResultSets(ps);  
  1. /**   
  2. *ResultSetHandler類的handleResultSets()方法實作 
  3. public List<Object> handleResultSets(Statement stmt) throws SQLException {  
  4.     final List<Object> multipleResults = new ArrayList<Object>();  
  5.     int resultSetCount = 0;  
  6.     ResultSetWrapper rsw = getFirstResultSet(stmt);  
  7.     List<ResultMap> resultMaps = mappedStatement.getResultMaps();  
  8.     int resultMapCount = resultMaps.size();  
  9.     validateResultMapsCount(rsw, resultMapCount);  
  10.     while (rsw != null && resultMapCount > resultSetCount) {  
  11.       ResultMap resultMap = resultMaps.get(resultSetCount);  
  12.       //将resultSet  
  13.       handleResultSet(rsw, resultMap, multipleResults, null);  
  14.       rsw = getNextResultSet(stmt);  
  15.       cleanUpAfterHandlingResultSet();  
  16.       resultSetCount++;  
  17.     String[] resultSets = mappedStatement.getResulSets();  
  18.     if (resultSets != null) {  
  19.       while (rsw != null && resultSetCount < resultSets.length) {  
  20.         ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]);  
  21.         if (parentMapping != null) {  
  22.           String nestedResultMapId = parentMapping.getNestedResultMapId();  
  23.           ResultMap resultMap = configuration.getResultMap(nestedResultMapId);  
  24.           handleResultSet(rsw, resultMap, null, parentMapping);  
  25.         rsw = getNextResultSet(stmt);  
  26.         cleanUpAfterHandlingResultSet();  
  27.         resultSetCount++;  
  28.     return collapseSingleResultList(multipleResults);  
從上述代碼我們可以看出,StatementHandler 的List<E> query(Statement statement, ResultHandler resultHandler)方法的實作,是調用了ResultSetHandler的handleResultSets(Statement) 方法。ResultSetHandler的handleResultSets(Statement) 方法會将Statement語句執行後生成的resultSet 結果集轉換成List<E> 結果集:
  1. //  
  2. // DefaultResultSetHandler 類的handleResultSets(Statement stmt)實作   
  3. //HANDLE RESULT SETS  
  4.   final List<Object> multipleResults = new ArrayList<Object>();  
  5.   int resultSetCount = 0;  
  6.   ResultSetWrapper rsw = getFirstResultSet(stmt);  
  7.   List<ResultMap> resultMaps = mappedStatement.getResultMaps();  
  8.   int resultMapCount = resultMaps.size();  
  9.   validateResultMapsCount(rsw, resultMapCount);  
  10.   while (rsw != null && resultMapCount > resultSetCount) {  
  11.     ResultMap resultMap = resultMaps.get(resultSetCount);  
  12.     //将resultSet  
  13.     handleResultSet(rsw, resultMap, multipleResults, null);  
  14.     rsw = getNextResultSet(stmt);  
  15.     cleanUpAfterHandlingResultSet();  
  16.     resultSetCount++;  
  17.   String[] resultSets = mappedStatement.getResulSets();  
  18.   if (resultSets != null) {  
  19.     while (rsw != null && resultSetCount < resultSets.length) {  
  20.       ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]);  
  21.       if (parentMapping != null) {  
  22.         String nestedResultMapId = parentMapping.getNestedResultMapId();  
  23.         ResultMap resultMap = configuration.getResultMap(nestedResultMapId);  
  24.         handleResultSet(rsw, resultMap, null, parentMapping);  
  25.   return collapseSingleResultList(multipleResults);  
由于上述的過程時序圖太過複雜,就不貼出來了,讀者可以下載下傳MyBatis源碼, 使用Eclipse、Intellij IDEA、NetBeans 等IDE內建環境建立項目,Debug MyBatis源碼,一步步跟蹤MyBatis的實作,這樣對學習MyBatis架構很有幫助~