Mybatis-TypeHandler源碼解析

Mybatis3.5.1源碼分析

  1. Mybatis-SqlSessionFactoryBuilder,XMLConfigBuilder,XPathParser源碼解析
  2. Mybatis-Configuration源碼解析
  3. Mybatis-事務(wù)對象源碼解析
  4. Mybatis-數(shù)據(jù)源源碼解析
  5. Mybatis緩存策略源碼解析
  6. Mybatis-DatabaseIdProvider源碼解析
  7. Mybatis-TypeHandler源碼解析
  8. Mybatis-Reflector源碼解析
  9. Mybatis-ObjectFactory,ObjectWrapperFactory源碼分析
  10. Mybatis-Mapper各類標(biāo)簽封裝類源碼解析
  11. Mybatis-XMLMapperBuilder,XMLStatmentBuilder源碼分析
  12. Mybatis-MapperAnnotationBuilder源碼分析
  13. [Mybatis-MetaObject,MetaClass源碼解析]http://www.itdecent.cn/p/f51fa552f30a)
  14. Mybatis-LanguageDriver源碼解析
  15. Mybatis-SqlSource源碼解析
  16. Mybatis-SqlNode源碼解析
  17. Mybatis-KeyGenerator源碼解析
  18. Mybatis-Executor源碼解析
  19. Mybatis-ParameterHandler源碼解析
  20. Mybatis-StatementHandler源碼解析
  21. Mybatis-DefaultResultSetHandler(一)源碼解析
  22. Mybatis-DefaultResultSetHandler(二)源碼解析
  23. Mybatis-ResultHandler,Cursor,RowBounds 源碼分析
  24. Mybatis-MapperProxy源碼解析
  25. Mybatis-SqlSession源碼解析
  26. Mybatis-Interceptor源碼解析

TypeHandler

/**
 *    Copyright 2009-2019 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.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 類型處理器
 * <p>
 *     無論是 MyBatis 在預(yù)處理語句(PreparedStatement)中設(shè)置一個參數(shù)時,還是從結(jié)果集中取出一個值時,
 *     都會用類型處理器將獲取的值以合適的方式轉(zhuǎn)換成 Java 類型
 * </p>
 *
 * @author Clinton Begin
 */
public interface TypeHandler<T> {

  /**
   * 把 java 對象設(shè)置到 PreparedStatement 的參數(shù)中
   * @param i 從1開始
   */
  void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;

  /**
   * 從 ResultSet 中取出columnName對應(yīng)數(shù)據(jù),然后轉(zhuǎn)換為 java 對象
   * @param columnName Colunm name, when configuration <code>useColumnLabel</code> is <code>false</code>
   */
  T getResult(ResultSet rs, String columnName) throws SQLException;

  /**
   * 用于從 ResultSet 或 CallableStatement 中取出數(shù)據(jù)轉(zhuǎn)換為 java 對象
   */
  T getResult(ResultSet rs, int columnIndex) throws SQLException;

  /**
   * 用于從 ResultSet 或 CallableStatement 中取出數(shù)據(jù)轉(zhuǎn)換為 java 對象
   */
  T getResult(CallableStatement cs, int columnIndex) throws SQLException;

}

BaseTypeHandler

/**
 *    Copyright 2009-2019 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.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.executor.result.ResultMapException;
import org.apache.ibatis.session.Configuration;

/**
 * The base {@link TypeHandler} for references a generic type.
 * 一個基本的{@link TypeHandler}引用了一個泛型類型
 * <p>
 * Important: Since 3.5.0, This class never call the {@link ResultSet#wasNull()} and
 * {@link CallableStatement#wasNull()} method for handling the SQL {@code NULL} value.
 * In other words, {@code null} value handling should be performed on subclass.
 * </p>
 * <p>
 *     重點(diǎn)聲明:自從3.5.0后,這個類不會再調(diào)用{@link ResultSet#wasNull()}和{@link CallableStatement#wasNull()}
 *     方法去處理null值的,換句話說,null值應(yīng)該交給子類處理。
 * </p>
 * @author Clinton Begin
 * @author Simone Tripodi
 * @author Kzuki Shimizu
 */
public abstract class BaseTypeHandler<T> extends TypeReference<T> implements TypeHandler<T> {

  /**
   * @deprecated Since 3.5.0 - See https://github.com/mybatis/mybatis-3/issues/1203. This field will remove future.
   */
  @Deprecated
  protected Configuration configuration;

  /**
   * @deprecated Since 3.5.0 - See https://github.com/mybatis/mybatis-3/issues/1203. This property will remove future.
   */
  @Deprecated
  public void setConfiguration(Configuration c) {
    this.configuration = c;
  }

  /**
   *  把 java 對象設(shè)置到 PreparedStatement 的參數(shù)中
   *  <p>
   *      解決 {@link @paramter} ,{@link @jdbcType} 的情況。
   *  </p>
   *  <ol>
   *      <li>{@link @jdbcType}為null,拋出 {@link TypeException},也就是說{@link @jdbcType}調(diào)用這個方法的時候就已經(jīng)確定了</li>
   *      <li>{@link @parameter}為null時,對第{@link @i}個'?'設(shè)置null值;否則,
   *      調(diào)用抽象方法{@link BaseTypeHandler#setNonNullParameter(PreparedStatement, int, Object, JdbcType)}</li>
   *  </ol>
   */
  @Override
  public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
    if (parameter == null) {
      //一般情況下,jdbcType到這個方法時就已經(jīng)確定了jdbcType.TYPE_CODE,
      if (jdbcType == null) {
        throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters.");
      }
      try {
        //設(shè)置null值。
        ps.setNull(i, jdbcType.TYPE_CODE);
      } catch (SQLException e) {
        throw new TypeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . "
              + "Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. "
              + "Cause: " + e, e);
      }
    } else {
      try {
        setNonNullParameter(ps, i, parameter, jdbcType);
      } catch (Exception e) {
        throw new TypeException("Error setting non null for parameter #" + i + " with JdbcType " + jdbcType + " . "
              + "Try setting a different JdbcType for this parameter or a different configuration property. "
              + "Cause: " + e, e);
      }
    }
  }

  /**
   * 用于從 ResultSet 或 CallableStatement 中取出數(shù)據(jù)轉(zhuǎn)換為 java 對象
   * <p>
   *     直接調(diào)用{@link BaseTypeHandler#getNullableResult(ResultSet, String)}
   * </p>
   */
  @Override
  public T getResult(ResultSet rs, String columnName) throws SQLException {
    try {
      return getNullableResult(rs, columnName);
    } catch (Exception e) {
      throw new ResultMapException("Error attempting to get column '" + columnName + "' from result set.  Cause: " + e, e);
    }
  }

  /**
   * 用于從 ResultSet 或 CallableStatement 中取出數(shù)據(jù)轉(zhuǎn)換為 java 對象
   * <p>
   *     直接調(diào)用{@link BaseTypeHandler#getNullableResult(ResultSet, int)}
   * </p>
   */
  @Override
  public T getResult(ResultSet rs, int columnIndex) throws SQLException {
    try {
      return getNullableResult(rs, columnIndex);
    } catch (Exception e) {
      throw new ResultMapException("Error attempting to get column #" + columnIndex + " from result set.  Cause: " + e, e);
    }
  }

  /**
   * 用于從 ResultSet 或 CallableStatement 中取出數(shù)據(jù)轉(zhuǎn)換為 java 對象
   * <p>
   *     直接調(diào)用{@link BaseTypeHandler#getNullableResult(CallableStatement, int)}
   * </p>
   */
  @Override
  public T getResult(CallableStatement cs, int columnIndex) throws SQLException {
    try {
      return getNullableResult(cs, columnIndex);
    } catch (Exception e) {
      throw new ResultMapException("Error attempting to get column #" + columnIndex + " from callable statement.  Cause: " + e, e);
    }
  }

  /**
   * 設(shè)置不為空的參數(shù)
   */
  public abstract void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;

  /**
   * 獲取可空的結(jié)果
   * @param columnName Colunm name, when configuration <code>useColumnLabel</code> is <code>false</code>
   */
  public abstract T getNullableResult(ResultSet rs, String columnName) throws SQLException;

  /**
   * 獲取可空的結(jié)果
   */
  public abstract T getNullableResult(ResultSet rs, int columnIndex) throws SQLException;

  /**
   * 獲取可空的結(jié)果
   */
  public abstract T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException;

}

ObjectTypeHandler

/**
 *    Copyright 2009-2015 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.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Object 類型處理器
 * @author Clinton Begin
 */
public class ObjectTypeHandler extends BaseTypeHandler<Object> {

  /**
   * 直接調(diào)用 {@link PreparedStatement#setObject(int, Object)}
   */
  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType)
      throws SQLException {
    ps.setObject(i, parameter);
  }

  /**
   * 直接調(diào)用 {@link ResultSet#getObject(String)}
   */
  @Override
  public Object getNullableResult(ResultSet rs, String columnName)
      throws SQLException {
    return rs.getObject(columnName);
  }

  /**
   * 直接調(diào)用 {@link ResultSet#getObject(int)}
   */
  @Override
  public Object getNullableResult(ResultSet rs, int columnIndex)
      throws SQLException {
    return rs.getObject(columnIndex);
  }

  /**
   * 直接調(diào)用 {@link CallableStatement#getObject(int)}
   */
  @Override
  public Object getNullableResult(CallableStatement cs, int columnIndex)
      throws SQLException {
    return cs.getObject(columnIndex);
  }
}

UnknowTypeHandler

/**
 *    Copyright 2009-2019 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.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.io.Resources;

/**
 * 未知類型處理器
 * <p>在{@link BaseTypeHandler}的抽象方法中根據(jù)返回的結(jié)果集提供的列去獲取對應(yīng)的TypeHandler時候,
 *    在獲取不到的情況下,就會使用{@link ObjectTypeHandler}處理</p>
 * @author Clinton Begin
 */
public class UnknownTypeHandler extends BaseTypeHandler<Object> {

  private static final ObjectTypeHandler OBJECT_TYPE_HANDLER = new ObjectTypeHandler();

  private TypeHandlerRegistry typeHandlerRegistry;

  public UnknownTypeHandler(TypeHandlerRegistry typeHandlerRegistry) {
    this.typeHandlerRegistry = typeHandlerRegistry;
  }

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType)
      throws SQLException {
    TypeHandler handler = resolveTypeHandler(parameter, jdbcType);
    handler.setParameter(ps, i, parameter, jdbcType);
  }

  @Override
  public Object getNullableResult(ResultSet rs, String columnName)
      throws SQLException {
    TypeHandler<?> handler = resolveTypeHandler(rs, columnName);
    return handler.getResult(rs, columnName);
  }

  @Override
  public Object getNullableResult(ResultSet rs, int columnIndex)
      throws SQLException {
    TypeHandler<?> handler = resolveTypeHandler(rs.getMetaData(), columnIndex);
    if (handler == null || handler instanceof UnknownTypeHandler) {
      handler = OBJECT_TYPE_HANDLER;
    }
    return handler.getResult(rs, columnIndex);
  }

  @Override
  public Object getNullableResult(CallableStatement cs, int columnIndex)
      throws SQLException {
    return cs.getObject(columnIndex);
  }

  /**
   * 解析獲取類型處理器
   * <p>根據(jù) {@code parameter} 和 {@code jdbcType} 獲取typeHandler實(shí)例</p>
   * @return {@code parameter} 為null 或者
   *    獲取不了對應(yīng){@code parameter} 和 {@code jdbcType} 的typeHanlder實(shí)例
   *    或者為typeHandler實(shí)例都為{@link UnknownTypeHandler}的實(shí)例的話,都會返回{@link #OBJECT_TYPE_HANDLER}
   */
  private TypeHandler<?> resolveTypeHandler(Object parameter, JdbcType jdbcType) {
    TypeHandler<?> handler;
    if (parameter == null) {
      handler = OBJECT_TYPE_HANDLER;
    } else {
      //獲取typeHandler實(shí)例
      handler = typeHandlerRegistry.getTypeHandler(parameter.getClass(), jdbcType);
      // check if handler is null (issue #270)
      if (handler == null || handler instanceof UnknownTypeHandler) {
        handler = OBJECT_TYPE_HANDLER;
      }
    }
    return handler;
  }

  /**
   * 解析獲取TypeHandler實(shí)例
   * <p>
   *     通過{@code rs}拿到結(jié)果集的描述信息{@link ResultSetMetaData},根據(jù)描述信息去拿到列名對應(yīng)的
   *     位置,再調(diào)用{@link #resolveTypeHandler(ResultSetMetaData, Integer)}獲取對應(yīng)的TypeHandler實(shí)例。
   * </p>
   * @param rs 結(jié)果集
   * @param column 列名
   * @return {@link TypeHandler} 實(shí)例;
   *    當(dāng) {@code handler} 為null或者 {@code handler} 為 {@link UnknownTypeHandler} 就會返回 {@link #OBJECT_TYPE_HANDLER}
   */
  private TypeHandler<?> resolveTypeHandler(ResultSet rs, String column) {
    try {
      //將所有列的列名,對應(yīng)的位置都拿出來放到columnIndexLookup中
      Map<String,Integer> columnIndexLookup;
      columnIndexLookup = new HashMap<>();
      ResultSetMetaData rsmd = rs.getMetaData();
      int count = rsmd.getColumnCount();
      for (int i = 1; i <= count; i++) {
        String name = rsmd.getColumnName(i);
        columnIndexLookup.put(name,i);
      }
      //拿到column對應(yīng)的位置
      Integer columnIndex = columnIndexLookup.get(column);
      TypeHandler<?> handler = null;
      if (columnIndex != null) {
        handler = resolveTypeHandler(rsmd, columnIndex);
      }
      if (handler == null || handler instanceof UnknownTypeHandler) {
        handler = OBJECT_TYPE_HANDLER;
      }
      return handler;
    } catch (SQLException e) {
      throw new TypeException("Error determining JDBC type for column " + column + ".  Cause: " + e, e);
    }
  }

  /**
   * 解析獲取TypeHandler實(shí)例
   * @param rsmd 結(jié)果集描述信息
   * @param columnIndex 指定的列位置
   * @return TypeHandler實(shí)例
   */
  private TypeHandler<?> resolveTypeHandler(ResultSetMetaData rsmd, Integer columnIndex) {
    TypeHandler<?> handler = null;
    //從columnIndex中獲取jdbcType,不會拋出異常,但是會返回null
    JdbcType jdbcType = safeGetJdbcTypeForColumn(rsmd, columnIndex);
    //從columnIndex中獲取javaType,不會拋出異常,但是會返回null
    Class<?> javaType = safeGetClassForColumn(rsmd, columnIndex);
    //根據(jù)現(xiàn)有的條件,盡可能的找到對應(yīng)的typeHandler實(shí)例
    if (javaType != null && jdbcType != null) {
      handler = typeHandlerRegistry.getTypeHandler(javaType, jdbcType);
    } else if (javaType != null) {
      handler = typeHandlerRegistry.getTypeHandler(javaType);
    } else if (jdbcType != null) {
      handler = typeHandlerRegistry.getTypeHandler(jdbcType);
    }
    return handler;
  }

  /**
   * 安全的從列中拿到j(luò)dbcType,這里的安全應(yīng)該是指捕捉的所有獲取過程中拋出的異常。
   * @param rsmd 結(jié)果集的描述信息
   * @param columnIndex 指定的列位置
   * @return {@link JdbcType},在獲取過程中拋出異常會返回 {@code null}
   */
  private JdbcType safeGetJdbcTypeForColumn(ResultSetMetaData rsmd, Integer columnIndex) {
    try {
      return JdbcType.forCode(rsmd.getColumnType(columnIndex));
    } catch (Exception e) {
      return null;
    }
  }

  /**
   * 安全的從列中拿到j(luò)avaType,這里的安全應(yīng)該是指捕捉的所有獲取過程中拋出的異常。
   * @param rsmd 結(jié)果集的描述信息
   * @param columnIndex 指定的列位置
   * @return {@link Class},在獲取過程中拋出異常會返回 {@code null}
   */
  private Class<?> safeGetClassForColumn(ResultSetMetaData rsmd, Integer columnIndex) {
    try {
      return Resources.classForName(rsmd.getColumnClassName(columnIndex));
    } catch (Exception e) {
      return null;
    }
  }
}

TypeHandlerRegistry

/**
 *    Copyright 2009-2019 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.type;

import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.Year;
import java.time.YearMonth;
import java.time.ZonedDateTime;
import java.time.chrono.JapaneseDate;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.ibatis.binding.MapperMethod.ParamMap;
import org.apache.ibatis.io.ResolverUtil;
import org.apache.ibatis.io.Resources;

/**
 * 類型處理注冊器
 *
 * <br/>
 * 參考博客:
 * <ol>
 *     <li><a href='http://www.itdecent.cn/p/93f6205fb0ba'>http://www.itdecent.cn/p/93f6205fb0ba</a></li>
 *     <li><a href='http://www.itdecent.cn/p/44d01981d698'>http://www.itdecent.cn/p/44d01981d698</a></li>
 * </ol>
 * @author Clinton Begin
 * @author Kazuki Shimizu
 */
public final class TypeHandlerRegistry {

  /**
   * 枚舉類JdbcType作為鍵,完成數(shù)據(jù)庫類型與類型處理器的對應(yīng)注冊
   */
  private final Map<JdbcType, TypeHandler<?>>  jdbcTypeHandlerMap = new EnumMap<>(JdbcType.class);

  /**
   * Java類型作為鍵,JdbcType與TypeHandler的映射關(guān)系作為value,完成Java類型、數(shù)據(jù)庫類型和類型處理器三者的對應(yīng)注冊
   */
  private final Map<Type, Map<JdbcType, TypeHandler<?>>> typeHandlerMap = new ConcurrentHashMap<>();

  /**
   * 對未知類型的注冊,如Object
   * 其實(shí)還是在{@link BaseTypeHandler}的抽象方法中根據(jù)返回的結(jié)果集提供的列去獲取對應(yīng)的TypeHandler時候,
   * 在獲取不到的情況下,就會使用{@link ObjectTypeHandler}處理
   */
  private final TypeHandler<Object> unknownTypeHandler = new UnknownTypeHandler(this);

  /**
   * 保存著所有的類型處理器實(shí)例,是以類型處理器的類類型為鍵值保存的,它可以統(tǒng)籌所有的類型處理器實(shí)例
   */
  private final Map<Class<?>, TypeHandler<?>> allTypeHandlersMap = new HashMap<>();

  /**
   * 空TypeHandler集合的標(biāo)識
   */
  private static final Map<JdbcType, TypeHandler<?>> NULL_TYPE_HANDLER_MAP = Collections.emptyMap();

  /**
   * 默認(rèn)的枚舉類型
   */
  private Class<? extends TypeHandler> defaultEnumTypeHandler = EnumTypeHandler.class;

  /**
   * 注冊一些基本的,常用的TypeHandler
   */
  public TypeHandlerRegistry() {
    register(Boolean.class, new BooleanTypeHandler());
    register(boolean.class, new BooleanTypeHandler());
    register(JdbcType.BOOLEAN, new BooleanTypeHandler());
    register(JdbcType.BIT, new BooleanTypeHandler());

    register(Byte.class, new ByteTypeHandler());
    register(byte.class, new ByteTypeHandler());
    register(JdbcType.TINYINT, new ByteTypeHandler());

    register(Short.class, new ShortTypeHandler());
    register(short.class, new ShortTypeHandler());
    register(JdbcType.SMALLINT, new ShortTypeHandler());

    register(Integer.class, new IntegerTypeHandler());
    register(int.class, new IntegerTypeHandler());
    register(JdbcType.INTEGER, new IntegerTypeHandler());

    register(Long.class, new LongTypeHandler());
    register(long.class, new LongTypeHandler());

    register(Float.class, new FloatTypeHandler());
    register(float.class, new FloatTypeHandler());
    register(JdbcType.FLOAT, new FloatTypeHandler());

    register(Double.class, new DoubleTypeHandler());
    register(double.class, new DoubleTypeHandler());
    register(JdbcType.DOUBLE, new DoubleTypeHandler());

    register(Reader.class, new ClobReaderTypeHandler());
    register(String.class, new StringTypeHandler());
    register(String.class, JdbcType.CHAR, new StringTypeHandler());
    register(String.class, JdbcType.CLOB, new ClobTypeHandler());
    register(String.class, JdbcType.VARCHAR, new StringTypeHandler());
    register(String.class, JdbcType.LONGVARCHAR, new StringTypeHandler());
    register(String.class, JdbcType.NVARCHAR, new NStringTypeHandler());
    register(String.class, JdbcType.NCHAR, new NStringTypeHandler());
    register(String.class, JdbcType.NCLOB, new NClobTypeHandler());
    register(JdbcType.CHAR, new StringTypeHandler());
    register(JdbcType.VARCHAR, new StringTypeHandler());
    register(JdbcType.CLOB, new ClobTypeHandler());
    register(JdbcType.LONGVARCHAR, new StringTypeHandler());
    register(JdbcType.NVARCHAR, new NStringTypeHandler());
    register(JdbcType.NCHAR, new NStringTypeHandler());
    register(JdbcType.NCLOB, new NClobTypeHandler());

    register(Object.class, JdbcType.ARRAY, new ArrayTypeHandler());
    register(JdbcType.ARRAY, new ArrayTypeHandler());

    register(BigInteger.class, new BigIntegerTypeHandler());
    register(JdbcType.BIGINT, new LongTypeHandler());

    register(BigDecimal.class, new BigDecimalTypeHandler());
    register(JdbcType.REAL, new BigDecimalTypeHandler());
    register(JdbcType.DECIMAL, new BigDecimalTypeHandler());
    register(JdbcType.NUMERIC, new BigDecimalTypeHandler());

    register(InputStream.class, new BlobInputStreamTypeHandler());
    register(Byte[].class, new ByteObjectArrayTypeHandler());
    register(Byte[].class, JdbcType.BLOB, new BlobByteObjectArrayTypeHandler());
    register(Byte[].class, JdbcType.LONGVARBINARY, new BlobByteObjectArrayTypeHandler());
    register(byte[].class, new ByteArrayTypeHandler());
    register(byte[].class, JdbcType.BLOB, new BlobTypeHandler());
    register(byte[].class, JdbcType.LONGVARBINARY, new BlobTypeHandler());
    register(JdbcType.LONGVARBINARY, new BlobTypeHandler());
    register(JdbcType.BLOB, new BlobTypeHandler());

    register(Object.class, unknownTypeHandler);
    register(Object.class, JdbcType.OTHER, unknownTypeHandler);
    register(JdbcType.OTHER, unknownTypeHandler);

    register(Date.class, new DateTypeHandler());
    register(Date.class, JdbcType.DATE, new DateOnlyTypeHandler());
    register(Date.class, JdbcType.TIME, new TimeOnlyTypeHandler());
    register(JdbcType.TIMESTAMP, new DateTypeHandler());
    register(JdbcType.DATE, new DateOnlyTypeHandler());
    register(JdbcType.TIME, new TimeOnlyTypeHandler());

    register(java.sql.Date.class, new SqlDateTypeHandler());
    register(java.sql.Time.class, new SqlTimeTypeHandler());
    register(java.sql.Timestamp.class, new SqlTimestampTypeHandler());

    register(String.class, JdbcType.SQLXML, new SqlxmlTypeHandler());

    register(Instant.class, new InstantTypeHandler());
    register(LocalDateTime.class, new LocalDateTimeTypeHandler());
    register(LocalDate.class, new LocalDateTypeHandler());
    register(LocalTime.class, new LocalTimeTypeHandler());
    register(OffsetDateTime.class, new OffsetDateTimeTypeHandler());
    register(OffsetTime.class, new OffsetTimeTypeHandler());
    register(ZonedDateTime.class, new ZonedDateTimeTypeHandler());
    register(Month.class, new MonthTypeHandler());
    register(Year.class, new YearTypeHandler());
    register(YearMonth.class, new YearMonthTypeHandler());
    register(JapaneseDate.class, new JapaneseDateTypeHandler());

    // issue #273
    register(Character.class, new CharacterTypeHandler());
    register(char.class, new CharacterTypeHandler());
  }

  /**
   * Set a default {@link TypeHandler} class for {@link Enum}.
   * A default {@link TypeHandler} is {@link org.apache.ibatis.type.EnumTypeHandler}.
   * <p>
   *     為枚舉類{@link Enum}設(shè)置默認(rèn)的{@link TypeHandler}.默認(rèn)是{@link EnumTypeHandler}
   * </p>
   * @param typeHandler a type handler class for {@link Enum}
   * @since 3.4.5
   */
  public void setDefaultEnumTypeHandler(Class<? extends TypeHandler> typeHandler) {
    this.defaultEnumTypeHandler = typeHandler;
  }

  /**
   * 是否存在對應(yīng) {@link @javaType} 的 {@link TypeHandler},直接調(diào)用{@link #hasTypeHandler(Class, JdbcType)}
   */
  public boolean hasTypeHandler(Class<?> javaType) {
    return hasTypeHandler(javaType, null);
  }

  /**
   * 是否存在對應(yīng){@link @javaTypeReference}的{@link TypeHandler},直接調(diào)用{@link #hasTypeHandler(TypeReference, JdbcType)},
   * 第二個參數(shù){@link @jdbcType}為null
   */
  public boolean hasTypeHandler(TypeReference<?> javaTypeReference) {
    return hasTypeHandler(javaTypeReference, null);
  }

  /**
   * 是否存在對應(yīng) {@link @javaType} 和 {@link @jdbcType} 的 {@link TypeHandler}
   * <p>
   *     先判斷{@link @javaType} 是否為null,若為null,直接返回false。
   *      再嘗試調(diào)用{@link #getTypeHandler(Type, JdbcType)}獲取TypeHandler不為null返回true
   * </p>
   */
  public boolean hasTypeHandler(Class<?> javaType, JdbcType jdbcType) {
    return javaType != null && getTypeHandler((Type) javaType, jdbcType) != null;
  }

  /**
   * 是否存在對應(yīng) {@link @javaTypeReference} 和 {@link @jdbcType} 的 {@link TypeHandler}
   * <p>
   *     先判斷{@link @javaTypeReference} 是否為null,若為null,直接返回false。
   *      再嘗試調(diào)用{@link #getTypeHandler(TypeReference, JdbcType)}獲取TypeHandler不為null返回true
   * </p>
   */
  public boolean hasTypeHandler(TypeReference<?> javaTypeReference, JdbcType jdbcType) {
    return javaTypeReference != null && getTypeHandler(javaTypeReference, jdbcType) != null;
  }

  /**
   * 獲取TypeHandler實(shí)例
   * <p>
   *     從{@link #allTypeHandlersMap} 中獲取對應(yīng){@link @handlerType}的{@link @handlerType}實(shí)例
   * </p>
   */
  public TypeHandler<?> getMappingTypeHandler(Class<? extends TypeHandler<?>> handlerType) {
    return allTypeHandlersMap.get(handlerType);
  }

  /**
   * 獲取TypeHandler實(shí)例
   * <p>
   *     將{@link @type}強(qiáng)轉(zhuǎn)為{@link Type},然后調(diào)用{@link #getTypeHandler(Type, JdbcType)},第二個參數(shù){@link @jdbcType}設(shè)置成null
   * </p>
   */
  public <T> TypeHandler<T> getTypeHandler(Class<T> type) {
    return getTypeHandler((Type) type, null);
  }

  /**
   * 獲取TypeHandler實(shí)例
   * <p>
   *     直接調(diào)用{@link #getTypeHandler(TypeReference, JdbcType)},第二個參數(shù){@link @jdbcType}設(shè)置成null
   * </p>
   */
  public <T> TypeHandler<T> getTypeHandler(TypeReference<T> javaTypeReference) {
    return getTypeHandler(javaTypeReference, null);
  }

  /**
   * 獲取TypeHandler實(shí)例
   * <p>
   *     從{@link #jdbcTypeHandlerMap}中獲取對應(yīng){@link @jdbcType}
   * </p>
   */
  public TypeHandler<?> getTypeHandler(JdbcType jdbcType) {
    return jdbcTypeHandlerMap.get(jdbcType);
  }

  /**
   * 獲取 TypeHandler
   * <p>
   *     將 {@link @type} 轉(zhuǎn)換 {@link Type} 類型,然后調(diào)用 {@link TypeHandlerRegistry#getTypeHandler(Class, JdbcType)}
   * </p>
   */
  public <T> TypeHandler<T> getTypeHandler(Class<T> type, JdbcType jdbcType) {
    return getTypeHandler((Type) type, jdbcType);
  }

  /**
   * 獲取 TypeHandler
   * <p>
   *     調(diào)用{@link @javaTypeReference}的{@link TypeReference#getRawType()}得到子類聲明的對 T 泛型的聲明的類型,
   *     然后傳給{@link #getTypeHandler(Type, JdbcType)}得到對應(yīng)的TypeHandler
   * </p>
   */
  public <T> TypeHandler<T> getTypeHandler(TypeReference<T> javaTypeReference, JdbcType jdbcType) {
    return getTypeHandler(javaTypeReference.getRawType(), jdbcType);
  }

  /**
   * 根據(jù) {@link @type} 和 {@link @jdbcType} 獲取對應(yīng)的 {@link TypeHandler}
   * <ol>
   *     <li>如果{@link @type}是{@link ParamMap}會直接返回null</li>
   *     <li>通過{@link #getJdbcHandlerMap(Type)}獲取dbcType、TypeHandler映射關(guān)系的map并賦值給{@link @jdbcHandlerMap}</li>
   *     <li>傳入{@link @jdbcType}到{@link @jdbcHandlerMap}中獲取對應(yīng)的TypeHandler并賦值給{@link @handler}</li>
   *     <li>如果{@link @handler}為null,就是沒有拿到對應(yīng)的TypeHandler,就會從{@link @jdbcHandlerMap}取出對應(yīng)'null'的TypeHandler</li>
   *     <li>如果{@link @handler}還為null,將{@link @jdbcHandlerMap}傳入{@link #pickSoleHandler(Map)},由Mybatis自己選擇一個TypeHandler</li>
   *     <li>如果{@link @handler}還為null,就等于沒救了,返回null</li>
   * </ol>
   */
  @SuppressWarnings("unchecked")
  private <T> TypeHandler<T> getTypeHandler(Type type, JdbcType jdbcType) {
    //{@link ParamMap)是一個HashMap<String,Object>的子類,它重寫了get方法,使得如果嘗試獲取它沒有的key,將會拋出{@link BindingException}
    if (ParamMap.class.equals(type)) {
      return null;
    }
    //獲取JdbcType、TypeHandler映射關(guān)系的map
    Map<JdbcType, TypeHandler<?>> jdbcHandlerMap = getJdbcHandlerMap(type);
    TypeHandler<?> handler = null;
    if (jdbcHandlerMap != null) {
      handler = jdbcHandlerMap.get(jdbcType);//獲取對應(yīng)jdbcType的TypeHandler
      //如果沒有拿到,調(diào)用獲取jdbcType為null值情況的TypeHandler
      if (handler == null) {
        handler = jdbcHandlerMap.get(null);
      }
      /**
       * 還是沒有拿到,就由Mybatis自己選擇一個TypeHandler:
       *     如果有多個不同類型的TypeHandler就無法選擇TypeHandler,只能返回null;
       *     但是如果只有一個類型的TypeHandler,但有多個同類型的TypeHandler實(shí)例,就取最后一個實(shí)例
       */
      if (handler == null) {
        // #591
        handler = pickSoleHandler(jdbcHandlerMap);
      }
    }
    // type drives generics here
    //就算handler=null,也不會拋出空指針或者轉(zhuǎn)換異常
    return (TypeHandler<T>) handler;
  }

  /**
   * 獲取JdbcType、TypeHandler映射關(guān)系的map
   * <p>
   *     先將{@link @type}傳入從{@link #typeHandlerMap}中獲取JdbcType、TypeHandler映射關(guān)系的map。如果找到就返回出去。
   *     如果沒有獲取到,判斷是不是枚舉類,還是普通java類。
   *
   * </p>
   * <p>
   *     枚舉類:
   *     <ol style='margin-top:0px;margin-bottom:0px'>
   *         <li>調(diào)用{@link #getJdbcHandlerMapForEnumInterfaces(Class, Class)} 遍歷枚舉類的接口獲取第一個對應(yīng)
   *            {@link @type}的JdbcType、TypeHandler映射關(guān)系的map</li>
   *         <li>若還是找不到,就構(gòu)建{@link #defaultEnumTypeHandler}的實(shí)例,作為{@link @clazz}
   *              對應(yīng)的JdbcType、TypeHandler映射關(guān)系的map設(shè)置到{@link #typeHandlerMap},
   *              然后重新到{@link #typeHandlerMap}返回出去,其實(shí)返回出去的按理來說就是{@link #defaultEnumTypeHandler}的實(shí)例</li>
   *         <li>找到就設(shè)置到{@link #typeHandlerMap}中,并返回對應(yīng)的JdbcType、TypeHandler映射關(guān)系的map</li>
   *     </ol>
   * </p>
   * <p>
   *     普通java類:
   *     <ol style='margin-top:0px;margin-bottom:0px'>
   *        <li>將{@link @type}傳入{@link #getJdbcHandlerMapForSuperclass}方法,遍歷父類獲取第一個對應(yīng)
   *              {@link @type}的JdbcType、TypeHandler映射關(guān)系的map</li>
   *        <li>若還是沒有找到,就直接將{@link #NULL_TYPE_HANDLER_MAP}作為對應(yīng){@link @type}的JdbcType、TypeHandler映射關(guān)系的map。
   *              然后返回null</li>
   *        <li>找到就設(shè)置到{@link #typeHandlerMap}中,并返回對應(yīng)的JdbcType、TypeHandler映射關(guān)系的map</li>
   *     </ol>
   * </p>
   */
  private Map<JdbcType, TypeHandler<?>> getJdbcHandlerMap(Type type) {
    Map<JdbcType, TypeHandler<?>> jdbcHandlerMap = typeHandlerMap.get(type);
    if (NULL_TYPE_HANDLER_MAP.equals(jdbcHandlerMap)) {//空TypeHandler標(biāo)識返回null也是符合場景的。
      return null;
    }
    //沒有找到該類的JdbcType、TypeHandler映射關(guān)系Map 而且 {@link @type} 是 Class類,
    if (jdbcHandlerMap == null && type instanceof Class) {
      Class<?> clazz = (Class<?>) type;
      if (Enum.class.isAssignableFrom(clazz)) {//屬于枚舉類型
        //clazz若是枚舉類型,clazz.getSuperclass()就得到j(luò)ava.lang.Enum,因?yàn)槊杜e類型不能extends,但是可以implement
        //下面代碼如果屬于內(nèi)部類,就會得到j(luò)ava.lang.Enum
        Class<?> enumClass = clazz.isAnonymousClass() ? clazz.getSuperclass() : clazz;
        //從枚舉類的接口獲取JdbcType、TypeHandler映射關(guān)系的map
        jdbcHandlerMap = getJdbcHandlerMapForEnumInterfaces(enumClass, enumClass);
        //還是沒有找到的話,就用defaultEnumTypeHandler的實(shí)例對象作為對應(yīng)enumClass的TypeHandler
        if (jdbcHandlerMap == null) {
          register(enumClass, getInstance(enumClass, defaultEnumTypeHandler));
          return typeHandlerMap.get(enumClass);
        }
      } else {
        //嘗試通過獲取父類去獲取JdbcType、TypeHandler映射關(guān)系Map
        jdbcHandlerMap = getJdbcHandlerMapForSuperclass(clazz);
      }
    }
    //沒有JdbcType、TypeHandler映射關(guān)系Map時,就用NULL_TYPE_HANDLER_MAP作為對應(yīng)type的JdbcType、TypeHandler映射關(guān)系Map
    typeHandlerMap.put(type, jdbcHandlerMap == null ? NULL_TYPE_HANDLER_MAP : jdbcHandlerMap);
    return jdbcHandlerMap;
  }

  /**
   * 從枚舉類的接口獲取JdbcType、TypeHandler映射關(guān)系的map
   * <p>
   *     通過遞歸該方法深入{@link @clazz}的所有接口,若找到{@link @clazz}接口對應(yīng)的JdbcType、TypeHandler映射關(guān)系map【{@link @jdbcHandlerMap}】,
   *     就會根據(jù){@link @jdbcHandlerMap}構(gòu)建出{@link @enumClazz}對應(yīng)的JdbcType、TypeHandler映射關(guān)系map。注意一下,
   *     只會找出第一個匹配的JdbcType、TypeHandler映射關(guān)系map賦值給{@link @jdbcHandlerMap}。若還是沒有找到JdbcType、TypeHandler映射關(guān)系map,
   *     就會返回null
   * </p>
   */
  private Map<JdbcType, TypeHandler<?>> getJdbcHandlerMapForEnumInterfaces(Class<?> clazz, Class<?> enumClazz) {
    for (Class<?> iface : clazz.getInterfaces()) {//獲取該枚舉類所實(shí)現(xiàn)的所有接口
      //嘗試通過接口類獲取JdbcType、TypeHandler映射關(guān)系的map
      Map<JdbcType, TypeHandler<?>> jdbcHandlerMap = typeHandlerMap.get(iface);
      //如果還是沒有找到,通過遞歸的方式,深入這個接口中看看還有沒有繼承接口,從那些接口里嘗試獲取JdbcType、TypeHandler映射關(guān)系的map
      if (jdbcHandlerMap == null) {
        jdbcHandlerMap = getJdbcHandlerMapForEnumInterfaces(iface, enumClazz);
      }
      //找到了與接口對應(yīng)的JdbcType、TypeHandler映射關(guān)系map后
      if (jdbcHandlerMap != null) {
        // Found a type handler regsiterd to a super interface
        //構(gòu)建一個新的JdbcType、TypeHandler映射關(guān)系map
        HashMap<JdbcType, TypeHandler<?>> newMap = new HashMap<>();
        /**
         * 將jdbcHandlerMap的元素添加給newMap:
         * 將jdbcHandlerMap的key作為newMap的key,
         *  傳入enumClazz以及通過jdbcHandlerMap的value獲取value的Class來構(gòu)建一個對應(yīng)該枚舉類的TypeHandler對象作為value
         */
        for (Entry<JdbcType, TypeHandler<?>> entry : jdbcHandlerMap.entrySet()) {
          // Create a type handler instance with enum type as a constructor arg
          newMap.put(entry.getKey(), getInstance(enumClazz, entry.getValue().getClass()));
        }
        /**
         * 在這里進(jìn)行方法返回,就說明該方法只會找出第一個匹配的JdbcType、TypeHandler映射關(guān)系map,
         * 就算真的有兩個匹配的JdbcType、TypeHandler映射關(guān)系map,也不會合并且其JdbcType、TypeHandler映射關(guān)系map
         */
        return newMap;
      }
    }
    return null;//實(shí)在沒有找到的話,返回null,也是很合理的。
  }

  /**
   * 通過獲取父類去獲取JdbcType、TypeHandler映射關(guān)系Map
   * <p>
   *     通過遞歸{@link @clazz}的父類,獲取第一個對應(yīng)父類的JdbcType、TypeHandler映射關(guān)系Map
   * </p>
   */
  private Map<JdbcType, TypeHandler<?>> getJdbcHandlerMapForSuperclass(Class<?> clazz) {
    Class<?> superclass =  clazz.getSuperclass();
    /**
     * 沒有獲取到父類 或者 遞歸父類去獲取JdbcType、TypeHandler映射關(guān)系Map,都到了Object,返回null也是理所當(dāng)然啦
     */
    if (superclass == null || Object.class.equals(superclass)) {
      return null;
    }
    Map<JdbcType, TypeHandler<?>> jdbcHandlerMap = typeHandlerMap.get(superclass);
    if (jdbcHandlerMap != null) {
      /**
       * 只會找出第一個匹配的JdbcType、TypeHandler映射關(guān)系map,
       * 就算真的有兩個匹配的JdbcType、TypeHandler映射關(guān)系map,也不會合并且其JdbcType、TypeHandler映射關(guān)系map
       */
      return jdbcHandlerMap;
    } else {
      //遞歸父類
      return getJdbcHandlerMapForSuperclass(superclass);
    }
  }

  /**
   * 取唯一的TypeHandler
   * <p>
   *     如果有多個不同類型的TypeHandler就無法選擇TypeHandler,只能返回null;
   *     但是如果只有一個類型的TypeHandler,但有多個同類型的TypeHandler實(shí)例,就取最后一個實(shí)例
   * </p>
   * @param jdbcHandlerMap
   * @return
   */
  private TypeHandler<?> pickSoleHandler(Map<JdbcType, TypeHandler<?>> jdbcHandlerMap) {

    TypeHandler<?> soleHandler = null;
    for (TypeHandler<?> handler : jdbcHandlerMap.values()) {
      if (soleHandler == null) {
        soleHandler = handler;//取最后一個實(shí)例
      } else if (!handler.getClass().equals(soleHandler.getClass())) {
        // More than one type handlers registered.
        //不只一個TypeHandler類型得情況下
        return null;
      }
    }
    return soleHandler;
  }

  /**
   * 獲取未知類型TypeHandler實(shí)例
   * @return  {@link #unknownTypeHandler}
   */
  public TypeHandler<Object> getUnknownTypeHandler() {
    return unknownTypeHandler;
  }

  /**
   * 注冊 jdbcType 對應(yīng)的 TypeHandler
   * <p>
   *     直接調(diào)用以{@link @jdbcType}作為key 和 {@link @handler}作為value加入到{@link #jdbcTypeHandlerMap}中
   * </p>
   * @param jdbcType
   * @param handler
   */
  public void register(JdbcType jdbcType, TypeHandler<?> handler) {
    jdbcTypeHandlerMap.put(jdbcType, handler);
  }

  //
  // REGISTER INSTANCE
  //

  // Only handler


  /**
   * 注冊TypeHandler
   * <ol>
   *     <li>先嘗試獲取注解{@link MappedTypes}聲明的類來調(diào)用{@link #register(Class, TypeHandler)}進(jìn)行注冊</li>
   *     <li>再嘗試將{@link @typeHandler}轉(zhuǎn)換成{@link TypeReference},從而獲取到聲明的泛型類型
   *              來調(diào)用{@link #register(Class, TypeHandler)}進(jìn)行注冊</li>
   *     <li>都沒有找到對應(yīng)的java類型,就把javaType設(shè)置為null,調(diào)用{@link #register(Class, TypeHandler)}進(jìn)行注冊</li>
   * </ol>
   */
  @SuppressWarnings("unchecked")
  public <T> void register(TypeHandler<T> typeHandler) {
    //一個標(biāo)記,當(dāng)注冊了handledType就會變成true
    boolean mappedTypeFound = false;
    //根據(jù)注解MappedType注冊TypeHandler
    MappedTypes mappedTypes = typeHandler.getClass().getAnnotation(MappedTypes.class);
    if (mappedTypes != null) {
      for (Class<?> handledType : mappedTypes.value()) {
        register(handledType, typeHandler);
        mappedTypeFound = true;
      }
    }
    //根據(jù)TypeReference聲明的泛型類型注冊TypeHandler
    // @since 3.1.0 - try to auto-discover the mapped type
    if (!mappedTypeFound && typeHandler instanceof TypeReference) {
      try {
        TypeReference<T> typeReference = (TypeReference<T>) typeHandler;
        register(typeReference.getRawType(), typeHandler);
        mappedTypeFound = true;
      } catch (Throwable t) {
        // maybe users define the TypeReference with a different type and are not assignable, so just ignore it
        //可能用戶定義的類型引用具有不同的類型,并且不可賦值,所以忽略它
      }
    }
    //都沒有找到對應(yīng)的java類型,就當(dāng)作null進(jìn)行注冊。
    if (!mappedTypeFound) {
      register((Class<T>) null, typeHandler);
    }
  }

  // java type + handler

  /**
   * 注冊 javaType -- TypeHandle
   * 將{@link @javaType} 強(qiáng)轉(zhuǎn)為 {@link Type}后,調(diào)用 {@link TypeHandlerRegistry#register(Type, TypeHandler)}
   */
  public <T> void register(Class<T> javaType, TypeHandler<? extends T> typeHandler) {
    register((Type) javaType, typeHandler);
  }


  /**
   * 注冊 javaType -- TypeHandle
   * <p>
   *    獲取{@link @typeHandler}的{@link MappedJdbcTypes}注解信息賦值給{@link @mappedJdbcTypes},
   *    在{@link @mappedJdbcTypes}不為null的情況下,遍歷@mappedJdbcType所支持的jdbcType,
   *    對其調(diào)用 {@link TypeHandlerRegistry#register(Class, JdbcType, Class)} 注冊,再判斷是否支持null的jdbcType,
   *    支持的將null作為{@link TypeHandlerRegistry#register(Class, JdbcType, Class)}的第二參數(shù)進(jìn)行調(diào)用;
   *    否則,直接將null作為{@link TypeHandlerRegistry#register(Class, JdbcType, Class)}的第二參數(shù)進(jìn)行調(diào)用
   * </p>
   */
  private <T> void register(Type javaType, TypeHandler<? extends T> typeHandler) {
    MappedJdbcTypes mappedJdbcTypes = typeHandler.getClass().getAnnotation(MappedJdbcTypes.class);
    if (mappedJdbcTypes != null) {
      for (JdbcType handledJdbcType : mappedJdbcTypes.value()) {
        register(javaType, handledJdbcType, typeHandler);
      }
      if (mappedJdbcTypes.includeNullJdbcType()) {//支持NULL的JdbcType
        register(javaType, null, typeHandler);
      }
    } else {
      register(javaType, null, typeHandler);
    }
  }

  /**
   * 注冊 TypeHandler
   * <p>
   *     獲取{@link @javaTypeReference}所聲明的泛型類型,調(diào)用{@link #register(Class, TypeHandler)}進(jìn)行注冊
   * </p>
   */
  public <T> void register(TypeReference<T> javaTypeReference, TypeHandler<? extends T> handler) {
    register(javaTypeReference.getRawType(), handler);
  }

  // java type + jdbc type + handler

  /**
   * 注冊TypeHandler
   * <p>
   *     將{@link @type}強(qiáng)轉(zhuǎn)成{@link Type},調(diào)用{@link #register(Type, JdbcType, TypeHandler)}進(jìn)行注冊
   * </p>
   */
  public <T> void register(Class<T> type, JdbcType jdbcType, TypeHandler<? extends T> handler) {
    register((Type) type, jdbcType, handler);
  }

  /**
   * 注冊 javaType -- jdbcType -- TypeHandler
   * <p>
   *     先從 {@link TypeHandlerRegistry#typeHandlerMap} 中獲取{@link @javaType}對應(yīng)的 JdbcType、TypeHandler映射關(guān)系的map
   *     并賦值給{@link @map},然后將{@link @jdbcType}作為key和{@link @handler}作為value設(shè)置到{@link @map}。
   *     簡單來說就是合并原有的,新建沒有的。
   *     最后還會獲取{@link @handler}的Class類作為key,{@link @handler}作為value設(shè)置到{@link #allTypeHandlersMap}中
   * </p>
   * <p>
   *     只要{@link @map} 是 null,或者是一個{@link TypeHandlerRegistry#NULL_TYPE_HANDLER_MAP}都會對{@link @map}重新實(shí)例化
   *     一個新的{@link HashMap}并調(diào)用加入到 {@link #typeHandlerMap} 中。
   * </p>
   */
  private void register(Type javaType, JdbcType jdbcType, TypeHandler<?> handler) {
    if (javaType != null) {
      Map<JdbcType, TypeHandler<?>> map = typeHandlerMap.get(javaType);
      if (map == null || map == NULL_TYPE_HANDLER_MAP) {//就算 null類型TypeHandler Map都會重新賦值
        map = new HashMap<>();
        typeHandlerMap.put(javaType, map);
      }
      map.put(jdbcType, handler);
    }
    allTypeHandlersMap.put(handler.getClass(), handler);
  }

  //
  // REGISTER CLASS
  //

  // Only handler type

  /**
   * 注冊TypeHandler
   * <p>
   *     通過注解{@link MappedTypes}獲取{@link @typeHandlerClass}能處理的java類型,逐一調(diào)用{@link #register(Class, Class)}進(jìn)行注冊,
   *     沒有注冊到指定類型+TypeHandler映射關(guān)系時,用null當(dāng)作javaTypeClass參數(shù),調(diào)用{@link #getInstance(Class, Class)}得到TypeHandler的實(shí)例,
   *     然后調(diào)用{@link #register(TypeHandler)}進(jìn)行注冊。
   * </p>
   */
  public void register(Class<?> typeHandlerClass) {
    //已注冊標(biāo)記,當(dāng)注冊了指定類型+TypeHandler映射關(guān)系后會設(shè)置為tue
    boolean mappedTypeFound = false;
    MappedTypes mappedTypes = typeHandlerClass.getAnnotation(MappedTypes.class);
    if (mappedTypes != null) {
      for (Class<?> javaTypeClass : mappedTypes.value()) {
        register(javaTypeClass, typeHandlerClass);
        mappedTypeFound = true;
      }
    }
    //沒有注冊到指定類型+TypeHandler映射關(guān)系,用null當(dāng)作javaTypeClass進(jìn)行注冊
    if (!mappedTypeFound) {
      register(getInstance(null, typeHandlerClass));//為啥不用register(Class, Class)方法呢,因?yàn)閚ull沒有Class
    }
  }

  // java type + handler type

  /**
   * 注冊TypeHandler
   * <p>
   *     調(diào)用{@link Resources#classForName(String)}獲取{@link @javaTypeClassName}和{@link @typeHandlerClassName}的Class,
   *     再調(diào)用{@link #register(Class, Class)}
   * </p>
   */
  public void register(String javaTypeClassName, String typeHandlerClassName) throws ClassNotFoundException {
    register(Resources.classForName(javaTypeClassName), Resources.classForName(typeHandlerClassName));
  }

  /**
   * 注冊TypeHandler
   * <p>
   *     傳入{@link @javaTypeClass}和{@link @typeHandlerClass}到{@link #getInstance(Class, Class)}中得到TypeHandler的實(shí)例對象,
   *     再調(diào)用{@link #register(TypeHandler)}進(jìn)行注冊
   * </p>
   */
  public void register(Class<?> javaTypeClass, Class<?> typeHandlerClass) {
    register(javaTypeClass, getInstance(javaTypeClass, typeHandlerClass));
  }

  // java type + jdbc type + handler type

  /**
   * 注冊TypeHandler
   * <p>
   *     傳入{@link @javaTypeClass}和{@link @typeHandlerClass}到{@link #getInstance(Class, Class)}中得到TypeHandler的實(shí)例對象,
   *     再調(diào)用{@link #register(Type, JdbcType, TypeHandler)}進(jìn)行注冊
   * </p>
   */
  public void register(Class<?> javaTypeClass, JdbcType jdbcType, Class<?> typeHandlerClass) {
    register(javaTypeClass, jdbcType, getInstance(javaTypeClass, typeHandlerClass));
  }

  // Construct a handler (used also from Builders)

  /**
   * 創(chuàng)建TypeHandler實(shí)例對象
   * <p>
   *   當(dāng){@link @javaTypeClass}不為null,會嘗試通過帶 Class 參數(shù)的構(gòu)造方法進(jìn)行實(shí)例化TypeHandler對象。
   *   如果沒有該構(gòu)造方法,就通過無參構(gòu)造方法實(shí)例化TypeHandler對象。
   * </p>
   */
  @SuppressWarnings("unchecked")
  public <T> TypeHandler<T> getInstance(Class<?> javaTypeClass, Class<?> typeHandlerClass) {
    if (javaTypeClass != null) {
      /**
       * 嘗試通過帶 Class 參數(shù)的構(gòu)造方法進(jìn)行實(shí)例化TypeHandler對象。因?yàn)闆]有檢查是否存在某個構(gòu)造函數(shù)的方法,所以
       * 使用捕捉異常的方式解決.
       */
      try {
        Constructor<?> c = typeHandlerClass.getConstructor(Class.class);
        return (TypeHandler<T>) c.newInstance(javaTypeClass);
      } catch (NoSuchMethodException ignored) {
        // ignored 忽略沒有該方法異常,使得執(zhí)行下面代碼。
      } catch (Exception e) {
        throw new TypeException("Failed invoking constructor for handler " + typeHandlerClass, e);
      }
    }
    //通過無參構(gòu)造方法實(shí)例化TypeHandler
    try {
      Constructor<?> c = typeHandlerClass.getConstructor();
      return (TypeHandler<T>) c.newInstance();
    } catch (Exception e) {
      throw new TypeException("Unable to find a usable constructor for " + typeHandlerClass, e);
    }
  }

  // scan

  /**
   * 掃描包中的 {@link TypeHandler} 的子類,并 調(diào)用 {@link TypeHandlerRegistry#register(TypeHandler)}
   * @param packageName
   */
  public void register(String packageName) {
    ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<>();
    //掃描 packageName 里的 {@link TypeHandler} 子類
    resolverUtil.find(new ResolverUtil.IsA(TypeHandler.class), packageName);
    //獲取符合條件的類
    Set<Class<? extends Class<?>>> handlerSet = resolverUtil.getClasses();
    for (Class<?> type : handlerSet) {
      //Ignore inner classes and interfaces (including package-info.java) and abstract classes
      //忽略內(nèi)部類,接口,和抽象類
      if (!type.isAnonymousClass() && !type.isInterface() && !Modifier.isAbstract(type.getModifiers())) {
        register(type);
      }
    }
  }

  // get information

  /**
   * 獲取所有已注冊的TypeHandler
   * @since 3.2.2
   */
  public Collection<TypeHandler<?>> getTypeHandlers() {
    return Collections.unmodifiableCollection(allTypeHandlersMap.values());
  }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容