主頁 > 後端開發 > 面試官問你Mybatis的Mapper代理 你能答多少

面試官問你Mybatis的Mapper代理 你能答多少

2021-11-01 06:08:13 後端開發

大家都知道我的風格,喜歡用故事帶入技術學習,

但是... 我講原始碼怎么用故事帶入呢?

用我的萬能故事模板,小明探寶旅程,

這天小明來到的Mybatis王國,他問門口老者,這城門上寫的是iBatis,怎么改成Mybatis了呢,

老者回答:哦,原本呀這是iBatis,這如今啊改名Mybatis了,

小明撓了撓頭,老者回答了問題,但又好像沒回答,

反正知道了,現在就是Mybatis,

小明知道Mybatis王國有一神奇之物,名為Mapper代理,

由于對此物的執著,小明帶著他的武器(IntelliJ IDEA)進入城內一探究竟,

一、好奇心

好奇心是驅動我們人類發展必不可少的因素之一,都說好奇心害死貓,這句話在技術領域是不成立的,身為技術人員一定要對事物充滿好奇(我說的是技術領域的事物,你可別對特叔叔的服務好奇,就去找特叔叔)

你平時用Mybatis沒有什么能讓你好奇的嗎?

你創建一個Mapper介面,然后寫一個Mapper.xml

最后直接使用Mapper介面就能進行增刪改查操作了,

首先它是個介面呀,其次他怎么知道執行什么操作呢?

不知道你好奇不好奇,反正我很好奇,就是因為這份好奇心,我才來了這場探險之旅,

二、崎嶇的路

我已經給大家趟平了路,有好奇心的同學可以跟著我的腳印來,或許你也能發現很多精彩,

首先得有小兒國,不對是有Mybatis王國,

pom.xml

添加maven依賴后記得reload專案,讓他去下載對應jar包到本地倉庫,

<dependencies>
    <!--Mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <!--mysql驅動-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
</dependencies>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="https://www.cnblogs.com/freeedu/p/com.mysql.jdbc.Driver"/>
                <property name="url" value="https://www.cnblogs.com/freeedu/p/jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8"/>
                <property name="username" value="https://www.cnblogs.com/freeedu/p/root"/>
                <property name="password" value="https://www.cnblogs.com/freeedu/p/123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="TestMapper.xml"/>
    </mappers>
</configuration>

TestMapper.java

package dao;

import entity.TestEntity;
import java.util.List;
/**
 * @author 木子的晝夜編程
 */
public interface TestMapper {
    List<TestEntity> list();
}

TestEntity.java

package entity;

import java.math.BigDecimal;
/**
 * @author 木子的晝夜編程
 */
public class TestEntity {
    private  Long id;
    private String name;
    private BigDecimal salary;
    // getter setter 
}

TestMapper.xml

<?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="dao.TestMapper">
    <!--查詢所有資料-->
    <select id="list"  resultType="entity.TestEntity">
        select * from test
    </select>

</mapper>

Test.java

import dao.TestMapper;
import entity.TestEntity;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author 木子的晝夜編程
 */
public class Test {
    public static void main(String[] args) throws IOException {
        // 1. mybatis 組態檔
        String resource = "mybatis-config.xml";
        // 2. 獲取輸入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 3. 創建SqlSessionFactory工廠 這一步會進行Mapper的動態代理操作
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 4. 創建SqlSession
        try (SqlSession session = sqlSessionFactory.openSession()) {
            // 5. 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
            TestMapper mapper = session.getMapper(TestMapper.class);
            // 6. 呼叫方法
            List<TestEntity> list = mapper.list();
            System.out.println(list);

        }
    }
}

經過我的探索,主要邏輯在第三步就完成了,那句話怎么說來著,偷天換日,

前邊我們文章寫到過:反射、動態代理、工廠模式

這里就是用了這2中技術,把我們的Mapper進行了包裝,你以為你用的是你自己的Mapper,但是,你以為的你以為就是對的嗎?是不對的,

1. 
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
2. 
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
3. 
super(new Configuration());
有一個屬性是:
protected final MapperRegistry mapperRegistry = new MapperRegistry(this);

畫了一個簡單的類圖,其實就是在讀取組態檔的時候創建了一個MapperRegistry

而這個MapperRegistry就是存盤寶藏(我們寫的介面Mapper的代理)的地方,

file

我們可以看到什么時候出來的MapperRegistry

那我們看一下什么時候用他的addMapper方法了,當然了還有addMappers方法

我們就盯著addMapper方法分析就闊以了,不必太執著

file

1. 上邊已經創建了parser
parser.parse()
2. 可以看到這里開始決議組態檔了 configuration就是我們組態檔的根節點
parseConfiguration(parser.evalNode("/configuration"));
3. 看Mapper的話就看這個 決議mappers其他的標簽可以先忽略
mapperElement(root.evalNode("mappers"));

private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
        // 開始回圈遍歷mappers的子標簽 他的子標簽可以使mapper、package
        for (XNode child : parent.getChildren()) {
            // 如果是package 巴拉巴拉一頓操作 我們不看這個
            if ("package".equals(child.getName())) {
                String mapperPackage = child.getStringAttribute("name");
                configuration.addMappers(mapperPackage);
            } else {
                // 我們看這個 獲取字標簽的屬性
                String resource = child.getStringAttribute("resource");
                String url = child.getStringAttribute("url");
                String mapperClass = child.getStringAttribute("class");
                if (resource != null && url == null && mapperClass == null) {
                    // 如果只配置了resource 我們只看這種方式 因為我們配置的就是這種
                    // 讀取資源
                    ErrorContext.instance().resource(resource);
                    InputStream inputStream = Resources.getResourceAsStream(resource);
                    // 轉成XMLMapperBuilder
                    XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
                    // 走決議
                    mapperParser.parse();
                } else if (resource == null && url != null && mapperClass == null) {
                    // 如果只配置了url
                    ErrorContext.instance().resource(url);
                    InputStream inputStream = Resources.getUrlAsStream(url);
                    XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
                    mapperParser.parse();
                } else if (resource == null && url == null && mapperClass != null) {
                    // 如果只配置了class
                    Class<?> mapperInterface = Resources.classForName(mapperClass);
                    configuration.addMapper(mapperInterface);
                } else {
                    // 一個mapper只能有一個屬性 或者是url 或者是 resource 或者是 class
                    // 如果你開發的時候報這個錯誤了 那你應該就是配置了多個屬性
                    // 經過我的驗證 確實是 信我就好
                    throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
                }
            }
        }
    }
}
XMLMapperBuilder.java
public void parse() {
    // 判斷是否決議過這個檔案 決議過的都放在一個set中
    if (!configuration.isResourceLoaded(resource)) {
        // 進過了一系列操作
        configurationElement(parser.evalNode("/mapper"));
        // 放入set中標記為已決議過資源
        configuration.addLoadedResource(resource);
        // 開始系結Mapper與Mapper.xml
        bindMapperForNamespace();
    }

    parsePendingResultMaps();
    parsePendingCacheRefs();
    parsePendingStatements();
}

private void bindMapperForNamespace() {
    // 獲取命名空間 dao.TestMapper
    String namespace = builderAssistant.getCurrentNamespace();
    // 如果沒有配置命名空間 是不會進行Mapepr與Mapper.xml的系結的
    // 如果namespace為空 前邊決議會直接報例外 不知道什么情況能走到這里
    if (namespace != null) {
      Class<?> boundType = null;
      try {
        // 獲取命名空間對應的類 TestMapper.class
        boundType = Resources.classForName(namespace);
      } catch (ClassNotFoundException e) {
          // 如果找不見類 就算了 因為不是必須的
          // 我們自己的業務上也可以參考這種寫法 其實就是
          // if 類存在 巴拉巴拉一頓操作
          // else 不操作 
      }
      if (boundType != null) {
        // 先判斷是否已經包含這個類了 其實是呼叫的mapperRegistry的hasMapper
        if (!configuration.hasMapper(boundType)) {
          // 這里是為了適配spring做了 設定了一個標記 防止多次加載這個資源
          // 可以看MapperAnnotationBuilder#loadXmlResource了解更多
          configuration.addLoadedResource("namespace:" + namespace);
          // 我們不關注那些 我們只關注這個 
          configuration.addMapper(boundType);
        }
      }
    }
  }

還是我們之前說的那句話,看代碼尤其是原始碼,千萬不要進黑洞,你一定要明確你這次看的目的是什么,

就像我上邊按個configuration.addLoadedResource("namespace:" + namespace); 這里你知道是為了適配Spring做了一個標記就可以了,至于為什么適配,怎么做到的適配你不用管,你這次的目的應該很明確,就是想探索Mapper代理是怎么代理的,所以千萬千萬不要陷進去,

Configuration.java
public <T> void addMapper(Class<T> type) {
    mapperRegistry.addMapper(type);
}

public class MapperRegistry {
  // 這個是對Configuration的一個參考 因為注冊的時候肯定會用到一些個配置
  private final Configuration config;
  // 百寶箱 最后會存放再這里 代理工廠 我們最后代碼呼叫getMapper就是用這個工廠給我們創建一個
  // 代理物件 我們前幾篇篇文章寫得反射、代理模式、工廠模式 很貼合這里
  private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();

  public MapperRegistry(Configuration config) {
    this.config = config;
  }

  // 獲取代理 代碼一般呼叫的就是這個方法
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    // 如沒有Mapper型別對應的工廠 拋例外
    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);
    }
  }
    
  // 判斷是否存在 hashMap的containsKey
  public <T> boolean hasMapper(Class<T> type) {
    return knownMappers.containsKey(type);
  }
  
  // 注冊Mapper
  public <T> void addMapper(Class<T> type) {
    // 判斷是不是介面型別 如果不是介面型別不做處理
    if (type.isInterface()) {
      // 如果已經存在了 那就不添加 拋例外 
      if (hasMapper(type)) {
        throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
      }
      // 標記是否加載成功
      boolean loadCompleted = false;
      try {
        // 先占位 占位是非常重要的
         // 如果不占位 就可能被嘗試自動系結  
        // 如果型別已經存在就不會嘗試 上邊那個判斷hasMapper就是在判斷這個
        // 沒有很理解 不過無所謂 意思就是這樣寫比較好
        knownMappers.put(type, new MapperProxyFactory<T>(type));
        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        // 決議進行一些初始化
        parser.parse();
        loadCompleted = true;
      } finally {
        // 如果沒有加載成功 從map中移除
        if (!loadCompleted) {
          knownMappers.remove(type);
        }
      }
    }
  }
  
}


看過我昨天文章的人都知道 接下來我們看一下媒婆MapperProxyFactory

// 媒婆 負責介紹物件  負責創建我們Mapper介面代理的工廠類
public class MapperProxyFactory<T> {
  // 介面的Class物件
  private final Class<T> mapperInterface;
  // 方法物件 與 方法物件的封裝
  private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
  // 建構式
  public MapperProxyFactory(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }
  
  public Class<T> getMapperInterface() {
    return mapperInterface;
  }

  public Map<Method, MapperMethod> getMethodCache() {
    return methodCache;
  }
  //創建代理物件
  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    // 創建一個代理類 并回傳 至于這個Proxy可以看我前邊動態代理的文章  
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(),
                                      new Class[] { mapperInterface },
                                      mapperProxy);
  }
  // 這里是傳入一個sql會話 然后創建一個Mapper介面代理類
  public T newInstance(SqlSession sqlSession) {
    // 在這里創建了Mapper的代理 這個代理實作了InvocationHandler(還是要看我前幾篇動態代理文章)  
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession,
                                                          mapperInterface,
                                                          methodCache);
    return newInstance(mapperProxy);
  }

}

MapperProxy.java

/**
 *    Copyright 2009-2017 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.binding;

import java.io.Serializable;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;

import org.apache.ibatis.lang.UsesJava7;
import org.apache.ibatis.reflection.ExceptionUtil;
import org.apache.ibatis.session.SqlSession;

// JKD動態代理 都需要實作InvocationHandler
// 具體代理的事情 在invoke中做
public class MapperProxy<T> implements InvocationHandler, Serializable {

  private static final long serialVersionUID = -6424540398559729838L;
  // sqlSession
  private final SqlSession sqlSession;
  // 介面物件型別 TestMapper
  private final Class<T> mapperInterface;
  // 接口中的方法 list 等 
  private final Map<Method, MapperMethod> methodCache;

  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
  }

  // 介面代理物件所有方法都會呼叫這里 
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      // 判斷是不是基礎方法 toString hashCode 如果是的話直接呼叫不需要代理
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        // 判斷是不是default修改的方法 是的話特殊處理  
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    // 一般我們會走到這里 
    // 快取有的話 取快取資料 沒有的話 創建資料 放入快取 
    // 朋友們 可以看到 Map是個很神奇的存在 哪兒都有
    // 所以面試錢準備 一定要準備map 相關知識
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

  private MapperMethod cachedMapperMethod(Method method) {
    // 先判斷有沒有  
    MapperMethod mapperMethod = methodCache.get(method);
    // 沒有   
    if (mapperMethod == null) {
      // 創建 
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      // 放入快取
      methodCache.put(method, mapperMethod);
    }
    // 回傳
    return mapperMethod;
  }
}


MapperMethod.java

package org.apache.ibatis.binding;

import org.apache.ibatis.annotations.Flush;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ParamNameResolver;
import org.apache.ibatis.reflection.TypeParameterResolver;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;

// 這個類可就厲害了 這是最核心的類 這里就是封裝了我們使用SqlSession的操作
public class MapperMethod {
  // Sql標簽的型別 Insert Update Delete Select
  private final SqlCommand command;
  // 方法的引數資訊 回傳資訊等  
  private final MethodSignature method;
  // 構造
  public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
    this.command = new SqlCommand(config, mapperInterface, method);
    this.method = new MethodSignature(config, mapperInterface, method);
  }
  // 這里就是封裝了SqlSession的一系列方法selectOne、select、insert、delete等
  public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    switch (command.getType()) {
      // 為什么我們經常說Insert update delete 三個標簽其實功能一樣
      // 平時只是語意上有區分 
      // 我們可以點進sqlSession原始碼看看 最后都是呼叫了update方法
      case INSERT: {
        // 處理引數
    	Object param = method.convertArgsToSqlCommandParam(args);
        // 呼叫sqlSessioninsert
        result = rowCountResult(sqlSession.insert(command.getName(), param));
        break;
      }
      case UPDATE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.update(command.getName(), param));
        break;
      }
      case DELETE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.delete(command.getName(), param));
        break;
      }
      // 如果是Select那就多了    
      case SELECT:
        // 如果回傳型別void 并且有自定義ResultHandler
        if (method.returnsVoid() && method.hasResultHandler()) {
          executeWithResultHandler(sqlSession, args);
          result = null;
        } else if (method.returnsMany()) {
            // 回傳型別多行
          result = executeForMany(sqlSession, args);
        } else if (method.returnsMap()) {
            // 范湖Map
          result = executeForMap(sqlSession, args);
        } else if (method.returnsCursor()) {
            // 回傳Cursor
          result = executeForCursor(sqlSession, args);
        } else {
          // 回傳單個  
          Object param = method.convertArgsToSqlCommandParam(args);
          result = sqlSession.selectOne(command.getName(), param);
        }
        break;
      case FLUSH:
          // 清空快取  
        result = sqlSession.flushStatements();
        break;
      default:
        // 這個一般不出現 除非你是個傻子 哈哈    
        throw new BindingException("Unknown execution method for: " + command.getName());
    }
    // 這里很有意思
    // 我們可能遇到過 查詢結果是基礎型別(boolean、char、byte、short、int、long、float、double)的話 很容易報空例外
    // 我們寫代碼一定注意了 基礎型別一定要保證有回傳值 否則你就用封裝型別Integer Double等
    if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
      throw new BindingException("Mapper method '" 
          + command.getName() 
          + " attempted to return null from a method with a primitive return type ("
          + method.getReturnType() + ").");
    }
    // 回傳結果  
    return result;
  }
  
  // insert update delete 回傳處理 rowCount是Sqlsession執行完回傳的受影響行數
  private Object rowCountResult(int rowCount) {
    final Object result;
    // 如果回傳型別是void 就直接回傳空  
    if (method.returnsVoid()) {
      result = null;
        // 回傳型別 Integer int
    } else if (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType())) {
      result = rowCount;
        // 回傳型別Long long
    } else if (Long.class.equals(method.getReturnType()) || Long.TYPE.equals(method.getReturnType())) {
      result = (long)rowCount;
        // 回傳型別Boolean boolean
    } else if (Boolean.class.equals(method.getReturnType()) || Boolean.TYPE.equals(method.getReturnType())) {
      result = rowCount > 0;
    } else {
        // 其他回傳型別 直接拋例外
      throw new BindingException("Mapper method '" + command.getName() + "' has an unsupported return type: " + method.getReturnType());
    }
    return result;
  }
  
  // 有自定義的ResuleHandler
  private void executeWithResultHandler(SqlSession sqlSession, Object[] args) {
    MappedStatement ms = sqlSession.getConfiguration().getMappedStatement(command.getName());
    // 
    if (void.class.equals(ms.getResultMaps().get(0).getType())) {
      throw new BindingException("method " + command.getName() 
          + " needs either a @ResultMap annotation, a @ResultType annotation," 
          + " or a resultType attribute in XML so a ResultHandler can be used as a parameter.");
    }
    // 
    Object param = method.convertArgsToSqlCommandParam(args);
    // 
    if (method.hasRowBounds()) {
      RowBounds rowBounds = method.extractRowBounds(args);
      sqlSession.select(command.getName(), param, rowBounds, method.extractResultHandler(args));
    } else {
      // 
      sqlSession.select(command.getName(), param, method.extractResultHandler(args));
    }
  }
  // 多潭訓傳結果
  private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
    // 回傳值  
    List<E> result;
    // 把引數轉換為ParamMap  
    Object param = method.convertArgsToSqlCommandParam(args);
    // 是否有分頁引數
    if (method.hasRowBounds()) {
      RowBounds rowBounds = method.extractRowBounds(args);
      result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
    } else {
      // 直接執行  sqlSession的selectList
      result = sqlSession.<E>selectList(command.getName(), param);
    }
    // class1.isAssignableFrom(class2)
    // 判斷 class2是否是class1的子類或者子介面
    if (!method.getReturnType().isAssignableFrom(result.getClass())) {
      // 如果回傳型別是Array 轉換為Array  
      if (method.getReturnType().isArray()) {
        return convertToArray(result);
      } else {
        // 否者轉換為宣告的集合集合
        return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
      }
    }
    return result;
  }
  // 回傳Cursor
  private <T> Cursor<T> executeForCursor(SqlSession sqlSession, Object[] args) {
    Cursor<T> result;
    Object param = method.convertArgsToSqlCommandParam(args);
    if (method.hasRowBounds()) {
      RowBounds rowBounds = method.extractRowBounds(args);
      result = sqlSession.<T>selectCursor(command.getName(), param, rowBounds);
    } else {
      result = sqlSession.<T>selectCursor(command.getName(), param);
    }
    return result;
  }
  // 轉換成集合
  private <E> Object convertToDeclaredCollection(Configuration config, List<E> list) {
    // 先創建一個宣告的集合型別的物件  
    Object collection = config.getObjectFactory().create(method.getReturnType());
    // 轉換為代理
    MetaObject metaObject = config.newMetaObject(collection);
    // 元素都放進去
    metaObject.addAll(list);
    return collection;
  }
  // 轉換成陣列
  @SuppressWarnings("unchecked")
  private <E> Object convertToArray(List<E> list) {
    // 創建陣列物件
    Class<?> arrayComponentType = method.getReturnType().getComponentType();
    Object array = Array.newInstance(arrayComponentType, list.size());
    // 判斷是不是基礎型別陣列 int[] longp[]
    if (arrayComponentType.isPrimitive()) {
      // 如果是基礎型別需要一個一個轉換
      for (int i = 0; i < list.size(); i++) {
        // 
        Array.set(array, i, list.get(i));
      }
      return array;
    } else {
      // 如果不是直接呼叫toArray轉換為Array
      return list.toArray((E[])array);
    }
  }
  // 回傳Map
  private <K, V> Map<K, V> executeForMap(SqlSession sqlSession, Object[] args) {
    Map<K, V> result;
    Object param = method.convertArgsToSqlCommandParam(args);
    if (method.hasRowBounds()) {
      RowBounds rowBounds = method.extractRowBounds(args);
      result = sqlSession.<K, V>selectMap(command.getName(), param, method.getMapKey(), rowBounds);
    } else {
      result = sqlSession.<K, V>selectMap(command.getName(), param, method.getMapKey());
    }
    return result;
  }
  
  // 自定義Map 
  // 我們業務中也可以參考這種寫法 就是重寫了get方法,如果沒有獲取元素就拋例外
  public static class ParamMap<V> extends HashMap<String, V> {

    private static final long serialVersionUID = -2212268410512043556L;

    @Override
    public V get(Object key) {
      if (!super.containsKey(key)) {
        throw new BindingException("Parameter '" + key + "' not found. Available parameters are " + keySet());
      }
      return super.get(key);
    }
  }
}


//  封裝了具體執行的動作
public static class SqlCommand {
    // xml的id  比如:list
    private final String name;
    // insert update delete 等型別
    private final SqlCommandType type;

    public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
      // 名稱 list
      final String methodName = method.getName();
      // 類 dao.TestMapper 
      final Class<?> declaringClass = method.getDeclaringClass();
      MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
          configuration);
      if (ms == null) {
        // 是否有Flush標簽  
        if (method.getAnnotation(Flush.class) != null) {
          name = null;
          // 設定型別為Flush
          type = SqlCommandType.FLUSH;
        } else {
          throw new BindingException("Invalid bound statement (not found): "
              + mapperInterface.getName() + "." + methodName);
        }
      } else {
        name = ms.getId();
        type = ms.getSqlCommandType();
        // 型別不識別 直接拋例外 INSERT, UPDATE, DELETE, SELECT, FLUSH;
        if (type == SqlCommandType.UNKNOWN) {
          throw new BindingException("Unknown execution method for: " + name);
        }
      }
    }

    public String getName() {
      return name;
    }

    public SqlCommandType getType() {
      return type;
    }

    private MappedStatement resolveMappedStatement(Class<?> mapperInterface, String methodName,
        Class<?> declaringClass, Configuration configuration) {
      // statementId ==> dao.TestMapper.list
      String statementId = mapperInterface.getName() + "." + methodName;
      // 如果已經有了 直接回傳
      if (configuration.hasStatement(statementId)) {
        return configuration.getMappedStatement(statementId);
      } else if (mapperInterface.equals(declaringClass)) {
        return null;
      }
      for (Class<?> superInterface : mapperInterface.getInterfaces()) {
        if (declaringClass.isAssignableFrom(superInterface)) {
          MappedStatement ms = resolveMappedStatement(superInterface, methodName,
              declaringClass, configuration);
          if (ms != null) {
            return ms;
          }
        }
      }
      return null;
    }
  }

  public static class MethodSignature {
    // 是否回傳多條結果
    private final boolean returnsMany;
    // 是否回傳Map
    private final boolean returnsMap;
    // 是否回傳void
    private final boolean returnsVoid;
    //是否回傳Cursor
    private final boolean returnsCursor;
    // 回傳型別
    private final Class<?> returnType;
    // mapKey
    private final String mapKey;
    // resultHandler 型別引數的位置
    private final Integer resultHandlerIndex;
    // rowBound型別引數的位置
    private final Integer rowBoundsIndex;
    // 引數處理器
    private final ParamNameResolver paramNameResolver;
  }

三、嘮嘮

探險的最后結果是我蒙了,看著看著,看得我心灰意冷了,

這個架構太牛了,各種封裝,各種模式,各種

最主要的是我們看到了,是用了代理模式和工廠模式,把我們的Mapper介面進行了代理,

我們通過getMapper獲取的介面其實就是代理物件,這時候所有操作都是通過代理MapperProxy

實作了InvocationHandler 進行的Jdk動態代理

我已經是第二次看原始碼了,依舊是不那么明朗,所以我們沒必要一次把所有的點都掌握,先掌握一個小點兒,比如先了解怎么通過動態代理實作的Mapper介面的代理,至于其他的代理的具體內容,再慢慢聊,


歡迎關注公眾號:木子的晝夜編程

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/342995.html

標籤:Java

上一篇:mybatis竟然報"Invalid value for getInt()"

下一篇:Spring Boot 如何獲取 Controller 方法名和注解資訊?

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more