请阐述 MyBatis 中 Executor 执行器的类型及其各自的特点,并说明它们之间的主要区别。
考察说明
考查对 MyBatis 核心组件 Executor 的理解,包括其分类和差异。
回答思路
- 【回答框架 1】MyBatis 的 Executor 是执行 SQL 的核心接口,负责 StatementHandler、ParameterHandler、ResultSetHandler 的调用。默认有三种:SimpleExecutor、ReuseExecutor、BatchExecutor,可通过 settings 的 defaultExecutorType 配置。
- 【回答框架 2】SimpleExecutor 每执行一次 SQL 就创建一个新的 Statement 对象,不重用,适合简单场景,但性能开销较大。ReuseExecutor 会缓存 Statement 对象,下次执行相同 SQL 时复用,减少创建和编译开销。BatchExecutor 用于批量操作,将多条 SQL 收集后一次性提交,减少数据库交互,但需注意其不支持查询操作,且批量更新需手动 flush。
- 【回答框架 3】三种执行器的主要区别在于 Statement 的复用策略和是否支持批量执行。SimpleExecutor 无复用,ReuseExecutor 按 SQL 缓存复用,BatchExecutor 支持批量。实际使用中,Spring 集成时可配置 ExecutorType,如 BATCH 用于批量插入。选择时需根据业务场景,批量操作选 BatchExecutor,普通查询用 Simple 或 Reuse。
- 【回答框架 4】此外,MyBatis 还有 CachingExecutor,它通过装饰器模式为 Executor 添加二级缓存功能,默认开启。CachingExecutor 包装底层 Executor,查询时先查缓存,未命中再委托给被包装的 Executor。因此,执行器实际是 CachingExecutor 包裹 Simple/Reuse/Batch 之一。
- 【关键点 1】MyBatis 有三种基础 Executor:SimpleExecutor、ReuseExecutor、BatchExecutor。
- 【关键点 2】ReuseExecutor 通过 Statement 缓存减少重复编译,BatchExecutor 用于批量更新。
- 【关键点 3】CachingExecutor 是装饰器,为 Executor 添加二级缓存能力,默认启用。
- 【关键点 4】选择 Executor 需结合场景:批量操作用 Batch,普通查询用 Simple 或 Reuse。
- 【易错点 1】BatchExecutor 不支持查询操作,若混用查询会导致结果异常。
- 【易错点 2】CachingExecutor 缓存可能导致脏数据,需注意缓存刷新策略。
- 【易错点 3】勿混淆 Executor 与 StatementHandler 的职责,前者负责整体执行流程,后者处理具体 SQL 语句。