mybatis源码分析 各大组件简介

本文详细介绍了MyBatis的各个核心组件,包括Configuration、Environment、TypeAliasRegistry、InterceptorChain、TypeHandlerRegistry、缓存配置、数据源配置、Mapper配置、SqlSession相关组件以及sql执行流程。内容涵盖从配置到执行的全过程,是理解MyBatis工作原理的绝佳参考资料。
摘要由CSDN通过智能技术生成

目录

主体配置

Configuration

Environment

TypeAliasRegistry

InterceptorChain

Interceptor

TypeHandlerRegistry

TypeHandler

缓存配置

Cache

PerpetualCache 

LruCache

BlockingCache

CacheKey

TransactionalCacheManager

TransactionalCache

数据源配置

DataSourceFactory

UnpooledDataSourceFactory

UnpooledDataSource

PooledDataSourceFactory

PooledDataSource

PoolState

PooledConnection 

mapper配置

ResultMap

ResultMapping

MappedStatement

KeyGenerator

SelectKeyGenerator

SqlSource

SqlSourceBuilder

DynamicSqlSource

RawSqlSource

StaticSqlSource

MixedSqlNode

StaticTextSqlNode

TextSqlNode

IfSqlNode

TrimSqlNode 

WhereSqlNode

SqlSession相关及四大对象

SqlSessionFactory

DefaultSqlSessionFactory

SqlSession

DefaultSqlSession

Executor

BaseExecutor

SimpleExecutor

BatchExecutor

ReuseExecutor

CachingExecutor

StatementHandler

BaseStatementHandler

SimpleStatementHandler

PreparedStatementHandler

CallableStatementHandler

RoutingStatementHandler

ParameterHandler

DefaultParameterHandler

ResultSetHandler

DefaultResultSetHandler

sql执行的其他相关

MapperRegistry

MapperProxyFactory

MapperMethod

SqlCommand 

MethodSignature 

BoundSql

DynamicContext

ParameterMapping

执行sql流程小结


主体配置

Configuration

有各种配置项,而且有对应的默认值。

有各种解析完后的MappedStatement,Cache,ResultMap,ParameterMap,KeyGenerator等。

有一个Environment

构造方法中注册了很多别名。

  //环境
  protected Environment environment;

  //---------以下都是<settings>节点-------
  protected boolean safeRowBoundsEnabled = false;
  protected boolean safeResultHandlerEnabled = true;
  protected boolean mapUnderscoreToCamelCase = false;
  protected boolean aggressiveLazyLoading = true;
  protected boolean multipleResultSetsEnabled = true;
  protected boolean useGeneratedKeys = false;
  protected boolean useColumnLabel = true;
  //默认启用缓存
  protected boolean cacheEnabled = true;
  protected boolean callSettersOnNulls = false;

  protected String logPrefix;
  protected Class <? extends Log> logImpl;
  protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
  protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
  protected Set<String> lazyLoadTriggerMethods = new HashSet<String>(Arrays.asList(new String[] { "equals", "clone", "hashCode", "toString" }));
  protected Integer defaultStatementTimeout;
  //默认为简单执行器
  protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
  protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
  //---------以上都是<settings>节点-------

  protected Properties variables = new Properties();
  //对象工厂和对象包装器工厂
  protected ObjectFactory objectFactory = new DefaultObjectFactory();
  protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();
  //映射注册机
  protected MapperRegistry mapperRegistry = new MapperRegistry(this);

  //默认禁用延迟加载
  protected boolean lazyLoadingEnabled = false;
  protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL

  protected String databaseId;
  /**
   * Configuration factory class.
   * Used to create Configuration for loading deserialized unread properties.
   *
   * @see <a href='https://code.google.com/p/mybatis/issues/detail?id=300'>Issue 300</a> (google code)
   */
  protected Class<?> configurationFactory;

  protected final InterceptorChain interceptorChain = new InterceptorChain();
  //类型处理器注册机
  protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry();
  //类型别名注册机
  protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry();
  protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry();

  //映射的语句,存在Map里
  protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection");
  //缓存,存在Map里
  protected final Map<String, Cache> caches = new StrictMap<Cache>("Caches collection");
  //结果映射,存在Map里
  protected final Map<String, ResultMap> resultMaps = new StrictMap<ResultMap>("Result Maps collection");
  protected final Map<String, ParameterMap> parameterMaps = new StrictMap<ParameterMap>("Parameter Maps collection");
  protected final Map<String, KeyGenerator> keyGenerators = new StrictMap<KeyGenerator>("Key Generators collection");

  protected final Set<String> loadedResources = new HashSet<String>();
  protected final Map<String, XNode> sqlFragments = new StrictMap<XNode>("XML fragments parsed from previous mappers");

  //不完整的SQL语句
  protected final Collection<XMLStatementBuilder> incompleteStatements = new LinkedList<XMLStatementBuilder>();
  protected final Collection<CacheRefResolver> incompleteCacheRefs = new LinkedList<CacheRefResolver>();
  protected final Collection<ResultMapResolver> incompleteResultMaps = new LinkedList<ResultMapResolver>();
  protected final Collection<MethodResolver> incompleteMethods = new LinkedList<MethodResolver>();

  /*
   * A map holds cache-ref relationship. The key is the namespace that
   * references a cache bound to another namespace and the value is the
   * namespace which the actual cache is bound to.
   */
  protected final Map<String, String> cacheRefMap = new HashMap<String, String>();

Environment

环境  决定加载哪种环境(开发环境/生产环境)

内部有一个Builder用来构建

  //环境id
  private final String id;
  //事务工厂
  private final TransactionFactory transactionFactory;
  //数据源
  private final DataSource dataSource;
<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="${jdbc.driver}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </dataSource>
    </environment>
</environments>

TypeAliasRegistry

类型别名注册机,里面有Map<String, Class<?>>类型的TYPE_ALIASES

同时注册了很多别名

InterceptorChain

拦截器链,内部就是一个拦截器的List,List<Interceptor>类型的interceptors

Interceptor

拦截器接口

  //拦截
  Object intercept(Invocation invocation) throws Throwable;

  //插入
  Object plugin(Object target);

  //设置属性
  void setProperties(Properties properties);

TypeHandlerRegistry

类型处理器注册机

自动注册了很多javatype和jdbctype的处理器

//枚举型map
  private final Map<JdbcType, TypeHandler<?>> JDBC_TYPE_HANDLER_MAP = new EnumMap<JdbcType, TypeHandler<?>>(JdbcType.class);
  private final Map<Type, Map<JdbcType, TypeHandler<?>>> TYPE_HANDLER_MAP = new HashMap<Type, Map<JdbcType, TypeHandler<?>>>();
  private final TypeHandler<Object> UNKNOWN_TYPE_HANDLER = new UnknownTypeHandler(this);
  private final Map<Class<?>, TypeHandler<?>> ALL_TYPE_HANDLERS_MAP = new HashMap<Class<?>, TypeHandler<?>>();

TypeHandler

类型处理器接口

  //设置参数
  void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;
  //取得结果,供普通select用
  T getResult(ResultSet rs, String columnName) throws SQLException;
  //取得结果,供普通select用
  T getResult(ResultSet rs, int columnIndex) throws SQLException;
  //取得结果,供SP用
  T getResult(CallableStatement cs, int columnIndex) throws SQLException;</
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值