MyBatis StatementHandler是如何创建 Statement 对象的? 如何执行 SQL 语句?

在MyBatis中,StatementHandler负责创建Statement对象并执行SQL语句。以下是其具体流程:
1. StatementHandler.prepare() 方法:创建 JDBC Statement 对象

StatementHandler.prepare(Connection connection, Integer transactionTimeout) 方法是核心方法,负责基于 MappedStatement 配置创建相应的 JDBC Statement 对象。

以下是 prepare() 方法内部发生步骤的分解:

  • 输入参数:

    • Connection connection:将用于创建 Statement 的 JDBC Connection 对象。此 Connection 通常由 MyBatis 的 Transaction 组件管理。
    • Integer transactionTimeout:一个可选的事务超时值(以秒为单位),用于 Statement
  • 确定 Statement 类型:
    StatementHandler 检查其持有的 MappedStatement 对象以确定 statementTypestatementType 在 Mapper XML 文件中通过