大家都知道我的風格,喜歡用故事帶入技術學習,
但是... 我講原始碼怎么用故事帶入呢?
用我的萬能故事模板,小明探寶旅程,
這天小明來到的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的代理)的地方,

我們可以看到什么時候出來的MapperRegistry
那我們看一下什么時候用他的addMapper方法了,當然了還有addMappers方法
我們就盯著addMapper方法分析就闊以了,不必太執著

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
