zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【项目实战】MyBatis的基础源码 —— MyBatis Executor 执行器(执行SQL语句的核心组件)源码

2023-09-14 09:04:55 时间

一、MyBatis执行器是什么?

它是负责执行SQL语句的核心组件之一。

二、MyBatis执行器的主要作用

它的主要作用是将用户传入的SQL语句转换为JDBC的PreparedStatement对象,并执行该对象的execute()方法来执行SQL语句。

三、MyBatis执行器的源码位置

在这里插入图片描述

四、MyBatis执行器的简单示例代码

以下是MyBatis执行器的简单示例代码:
在这里插入图片描述

public interface Executor {
    ResultHandler NO_RESULT_HANDLER = null;

    int update(MappedStatement ms, Object parameter) throws SQLException;

    <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException;

    <E> Cursor<E> queryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds) throws SQLException;

    List<BatchResult> flushStatements() throws SQLException;

    void commit(boolean required) throws SQLException;

    void rollback(boolean required) throws SQLException;

    CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql);

    boolean isCached(MappedStatement ms, CacheKey key);

    void clearLocalCache();

    void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key, Class<?> targetType);

    Transaction getTransaction();

    void close(boolean forceRollback);

    boolean isClosed();

    void setExecutorWrapper(Executor executor);
}

在上面的示例中,可以看到Executor接口

4.1 Executor接口定义了一些执行SQL语句的方法

例如update()、query()、queryCursor()等。
其中,

  • update()方法用于执行更新操作,
  • query()方法用于执行查询操作,
  • queryCursor()方法用于执行查询操作并返回一个Cursor对象。

4.2 Executor接口还定义了一些其他的方法

此外,Executor接口还定义了一些其他的方法
例如commit()、rollback()、clearLocalCache()等,用于事务管理和缓存管理。