【12.MyBatis源码剖析与架构实战】3.Executor源码剖析
MyBatis Executor 源码深度剖析Executor是 MyBatis 中负责 SQL 执行和缓存管理的核心接口,位于SqlSession之下,是真正与数据库交互的组件。本文将深入剖析Executor的继承体系、核心实现类(BaseExecutor、SimpleExecutor、ReuseExecutor、BatchExecutor、CachingExecutor),以及一级缓存、二级缓存、事务控制等关键机制。一、Executor 接口定义publicinterfaceExecutor{// 结果处理器标记(表示无自定义处理器)ResultHandlerNO_RESULT_HANDLER=null;// 查询方法(带分页和结果处理器)EListEquery(MappedStatementms,Objectparameter,RowBoundsrowBounds,ResultHandlerresultHandler)throwsSQLException;EListEquery(MappedStatementms,Objectparameter,RowBoundsrowBounds,ResultHandlerresultHandler,CacheKeykey,BoundSqlboundSql)throwsSQLException;// 刷新批处理语句(BatchExecutor 使用)ListBatchResultflushStatements()throwsSQLException;// 更新操作(insert/update/delete)intupdate(MappedStatementms,Objectparameter)throwsSQLException;// 事务提交voidcommit(booleanrequired)throwsSQLException;// 事务回滚voidrollback(booleanrequired)throwsSQLException;// 创建缓存键(用于一级/二级缓存)CacheKeycreateCacheKey(MappedStatementms,ObjectparameterObject,RowBoundsrowBounds,BoundSqlboundSql);// 判断是否缓存命中(仅用于二级缓存)booleanisCached(MappedStatementms,CacheKeykey);// 清空本地缓存(一级缓存)voidclearLocalCache();// 延迟加载(处理嵌套查询)voiddeferLoad(MappedStatementms,MetaObjectresultObject,Stringproperty,CacheKeykey,Class?targetType);// 获取事务TransactiongetTransaction();// 关闭执行器voidclose(booleanforceRollback);// 是否已关闭booleanisClosed();// 设置执行器包装器(用于插件链)voidsetExecutorWrapper(Executorexecutor);}二、Executor 继承体系«interface»Executor+query()+update()+commit()+rollback()+flushStatements()«abstract»BaseExecutor#PerpetualCache localCache#PerpetualCache localOutputParameterCache#Transaction transaction#boolean closed