MyBatis 中 StatementHandler 和 MappedStatement 区别?

在MyBatis中,StatementHandlerMappedStatement是两个不同的概念,它们有着不同的职责和用途:

  1. MappedStatement:它是MyBatis中一个非常重要的角色。每一个<select/><insert/><update/><delete/>标签对应一个MappedStatement对象,它用于描述如何在数据库上执行SQL。MappedStatement对象包括了SQL语句、输入参数映射和返回结果映射等信息。

  2. StatementHandler:它是MyBatis的执行层,负责通过java.sql.Statement接口与数据库进行交互。StatementHandler接口有两个实现类,RoutingStatementHandlerBaseStatementHandlerRoutingStatementHandler是真正的StatementHandler实现类,它会根据StatementType决定生成哪一种BaseStatementHandler实现类,如PreparedStatementHandlerSimpleStatementHandlerCallableStatementHandler

在执行具体的SQL操作时,MyBatis会首先根据SQL ID找到对应的MappedStatement,然后通过MappedStatement创建一个StatementHandlerStatementHandler负责与JDBC进行交互,包括设置SQL参数、执行SQL、处理结果集等。

总的来说,MappedStatement是对SQL语句及其输入输出映射的封装;而StatementHandler则是负责使用JDBC执行SQL语句的处理器。

发表评论

后才能评论