在MyBatis中,StatementHandler负责创建Statement对象并执行SQL语句。以下是其具体流程:
1. StatementHandler.prepare() 方法:创建 JDBC Statement 对象
StatementHandler.prepare(Connection connection, Integer transactionTimeout) 方法是核心方法,负责基于 MappedStatement 配置创建相应的 JDBC Statement 对象。
以下是 prepare() 方法内部发生步骤的分解:
-
输入参数:
Connection connection:将用于创建Statement的 JDBCConnection对象。此Connection通常由 MyBatis 的Transaction组件管理。Integer transactionTimeout:一个可选的事务超时值(以秒为单位),用于Statement。
-
确定
Statement类型:
StatementHandler检查其持有的MappedStatement对象以确定statementType。statementType在 Mapper XML 文件中通过<select>、<insert>、<update>、<delete>元素中的statementType属性进行配置。可能的取值包括:STATEMENT:用于普通的java.sql.Statement。PREPARED:用于java.sql.PreparedStatement(默认且最常用)。CALLABLE:用于java.sql.CallableStatement(用于存储过程/函数)。
-
创建 JDBC
Statement对象:
基于确定的statementType,StatementHandler使用提供的Connection对象来创建相应的 JDBCStatement实例:-
statementType="STATEMENT"(SimpleStatementHandler):Statement statement = connection.createStatement(); // 使用 Connection.createStatement()SimpleStatementHandler使用connection.createStatement()创建一个普通的Statement对象。 这是最简单的类型,适用于没有参数的基本 SQL。 -
statementType="PREPARED"(PreparedStatementHandler- 默认):PreparedStatement statement =
-

最低0.47元/天 解锁文章
1185

被折叠的 条评论
为什么被折叠?



