Mybatis源码-cursor(游标)

今天学习一下cursor包的下源码,了解mybatis大致游标实现

目录

    • 1、Cursor(游标接口类)
      • 1.1源码
      • 1.2总结
    • 2、DefaultCursor(默认游标实现类)
      • 2.1、源码
      • 2.2、总结

1、Cursor(游标接口类)

1.1源码

/**
 *    Copyright 2009-2019 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.cursor;

import java.io.Closeable;

/**
 * 这个游标通过迭代器来获取一条条数据
 * 游标非常适合处理数百万查询数据,这个样百万数据并不适合内存中获取
 * 如果在resultMap去收集结果,那么sql查询必须是有序的即设置(在id列进行设置resultOrdered="true")
 * Cursor contract to handle fetching items lazily using an Iterator.
 * Cursors are a perfect fit to handle millions of items queries that would not normally fits in memory.
 * If you use collections in resultMaps then cursor SQL queries must be ordered (resultOrdered="true")
 * using the id columns of the resultMap.
 *
 * @author Guillaume Darmont / [email protected]
 */
public interface Cursor<T> extends Closeable, Iterable<T> {

  /**游标开始从数据库获取数据这个就返回true
   * @return true if the cursor has started to fetch items from database.
   */
  boolean isOpen();

  /**
   * 判断所有元素是否已经获取完
   * @return true if the cursor is fully consumed and has returned all elements matching the query.
   */
  boolean isConsumed();

  /**
   * 获取数据的索引,从0开始,如果没有数据就返回-1
   * Get the current item index. The first item has the index 0.
   * @return -1 if the first cursor item has not been retrieved. The index of the current item retrieved.
   */
  int getCurrentIndex();
}

1.2总结

  1. 游标继承Closeable接口,这个接口只有一个close方法需要实现,一般用于资源需要手动关闭情况,各种io流之类这里是结果集(ResultSet需要关闭,所以继承这个接口)
  2. 继承Iterable接口,游标对结果集(ResultSet)进行遍历功能,需要实现一个迭代器的功能。

2、DefaultCursor(默认游标实现类)

2.1、源码

/**
 *    Copyright 2009-2019 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.cursor.defaults;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.NoSuchElementException;

import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.executor.resultset.DefaultResultSetHandler;
import org.apache.ibatis.executor.resultset.ResultSetWrapper;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

/**
 * 这个默认实现,它线程不安全的
 * This is the default implementation of a MyBatis Cursor.
 * This implementation is not thread safe.
 *
 * @author Guillaume Darmont / [email protected]
 */
public class DefaultCursor<T> implements Cursor<T> {

  // ResultSetHandler stuff
  /**
   * 默认结果集处理类
   */
  private final DefaultResultSetHandler resultSetHandler;

  /**
   * 结果map映射关系
   */
  private final ResultMap resultMap;

  /**
   * 结果集包装类
   */
  private final ResultSetWrapper rsw;

  /**
   * 物理分页
   */
  private final RowBounds rowBounds;

  /**
   * 对象包装结果处理类
   */
  private final ObjectWrapperResultHandler<T> objectWrapperResultHandler = new ObjectWrapperResultHandler<>();

  /**
   * 游标迭代器
   */
  private final CursorIterator cursorIterator = new CursorIterator();

  /**
   * 不能多次打开游标,只能打开一次
   */
  private boolean iteratorRetrieved;

  /**
   * 游标的默认状态是创建
   */
  private CursorStatus status = CursorStatus.CREATED;

  /**
   * 分页对象的索引位置为-1
   */
  private int indexWithRowBound = -1;

  /**
   * 游标的状态
   */
  private enum CursorStatus {

    /**
     * 刚刚出炉的游标,数据库的结果集还没有被消费
     * A freshly created cursor, database ResultSet consuming has not started.
     */
    CREATED,
    /**游标已经被使用,同时结果集数据已经开始被使用了
     * A cursor currently in use, database ResultSet consuming has started.
     */
    OPEN,
    /**
     * 游标被关闭,可能并没有全部被消费掉
     * A closed cursor, not fully consumed.
     */
    CLOSED,

    /**
     * 表示游标已经遍历所有数据集,这个消费完游标一直将会被关闭掉
     * A fully consumed cursor, a consumed cursor is always closed.
     */
    CONSUMED
  }

  /**
   * 创建一个默认的游标
   * @param resultSetHandler 默认结果集处理类
   * @param resultMap 结果映射map
   * @param rsw 结果集包装类
   * @param rowBounds 分页对象
   */
  public DefaultCursor(DefaultResultSetHandler resultSetHandler, ResultMap resultMap, ResultSetWrapper rsw, RowBounds rowBounds) {
    this.resultSetHandler = resultSetHandler;
    this.resultMap = resultMap;
    this.rsw = rsw;
    this.rowBounds = rowBounds;
  }

  /**
   * 判断是否被打开
   * @return
   */
  @Override
  public boolean isOpen() {
    return status == CursorStatus.OPEN;
  }

  /**
   * 判断游标是否被消费掉
   * @return
   */
  @Override
  public boolean isConsumed() {
    return status == CursorStatus.CONSUMED;
  }

  /**
   * 获取当前的索引
   * 分页偏移量+游标迭代器索引位置
   * @return
   */
  @Override
  public int getCurrentIndex() {
    return rowBounds.getOffset() + cursorIterator.iteratorIndex;
  }

  /**
   * 进行获取迭代器
   * @return
   */
  @Override
  public Iterator<T> iterator() {
    //判断是否已经获取过一次迭代器了
    //判断迭代器是否关闭
    if (iteratorRetrieved) {
      throw new IllegalStateException("Cannot open more than one iterator on a Cursor");
    }
    if (isClosed()) {
      throw new IllegalStateException("A Cursor is already closed.");
    }
    iteratorRetrieved = true;
    return cursorIterator;
  }

  /**
   * 关闭游标
   */
  @Override
  public void close() {
    //如果游标已经关闭直接返回
    //获取结果集,如果结果集不为空,直接关闭,忽略关闭后异常
    //修改游标的状态为关闭
    if (isClosed()) {
      return;
    }

    ResultSet rs = rsw.getResultSet();
    try {
      if (rs != null) {
        rs.close();
      }
    } catch (SQLException e) {
      // ignore
    } finally {
      status = CursorStatus.CLOSED;
    }
  }

  protected T fetchNextUsingRowBound() {
    T result = fetchNextObjectFromDatabase();
    // 过滤到偏移量的位置
    while (result != null && indexWithRowBound < rowBounds.getOffset()) {
      result = fetchNextObjectFromDatabase();
    }
    return result;
  }

  /**
   * 从数据库中获取下一个对象
   * @return
   */
  protected T fetchNextObjectFromDatabase() {
    //判断游标是否已经关闭,已关闭返回null
    if (isClosed()) {
      return null;
    }
    // 设置当前状态是游标打开状态
    // 如果结果集包装类不是已经关闭
    // 把结果放入objectWrapperResultHandler对象的result中
    try {
      status = CursorStatus.OPEN;
      if (!rsw.getResultSet().isClosed()) {
        resultSetHandler.handleRowValues(rsw, resultMap, objectWrapperResultHandler, RowBounds.DEFAULT, null);
      }
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
    // 获取对象包装处理的结果
    // 如果结果不为空结果, 索引++
    T next = objectWrapperResultHandler.result;
    if (next != null) {
      indexWithRowBound++;
    }
    // No more object or limit reached
    //next为null或者读取条数等于偏移量+限制条数
    if (next == null || getReadItemsCount() == rowBounds.getOffset() + rowBounds.getLimit()) {
      close();
      status = CursorStatus.CONSUMED;
    }
    //把结果设置为null
    objectWrapperResultHandler.result = null;

    return next;
  }

  /**
   * 判断是否关闭
   * 游标本身处于关闭状态,或者已经取出结果的所有元素
   * @return
   */
  private boolean isClosed() {
    return status == CursorStatus.CLOSED || status == CursorStatus.CONSUMED;
  }

  /**
   * 下一个读取索引位置
   * @return
   */
  private int getReadItemsCount() {
    return indexWithRowBound + 1;
  }

  /**
   * 对象结果集包装类
   * @param 
   */
  private static class ObjectWrapperResultHandler<T> implements ResultHandler<T> {

    /**
     * 结果集
     */
    private T result;

    /**
     * 上下文中获取结果集
     * @param context
     */
    @Override
    public void handleResult(ResultContext<? extends T> context) {
      this.result = context.getResultObject();
      context.stop();
    }
  }

  /**
   * 创建一个游标迭代器对象
   */
  private class CursorIterator implements Iterator<T> {

    /**
     * 保存下一个将会被返回的对象
     * Holder for the next object to be returned.
     */
    T object;

    /**返回下一个对象的索引
     * Index of objects returned using next(), and as such, visible to users.
     */
    int iteratorIndex = -1;

    /**
     * 是否有下个
     * @return
     */
    @Override
    public boolean hasNext() {
      if (object == null) {
        object = fetchNextUsingRowBound();
      }
      return object != null;
    }

    /**
     * 判断下一个值
     * @return
     */
    @Override
    public T next() {
      // Fill next with object fetched from hasNext()
      //执行过haNext()方法object的值才不会为null
      T next = object;
      //表示没有执行hasNext()方法,所以在获取一次数据
      if (next == null) {
        next = fetchNextUsingRowBound();
      }

      if (next != null) {
        object = null;
        iteratorIndex++;
        return next;
      }
      throw new NoSuchElementException();
    }

    /**
     * 不支持删除对象
     */
    @Override
    public void remove() {
      throw new UnsupportedOperationException("Cannot remove element from Cursor");
    }
  }
}

2.2、总结

  1. 这个默认实现是线程不安全的
  2. ResultSetWrapper: 从数据库查询原始结果集
  3. ResultMap: xml或java注解配置结果的映射关系(数据库与java实体类之间的关系)
  4. DefaultResultSetHandler : 真正实现原始的结果集转成Java实体类的工具处理类
  5. ObjectWrapperResultHandler:DefaultResultSetHandler 处理后生成中间产物(上下文信息),也就是从这个对象中拿去转换成java实体类T
  6. RowBounds: 分页实体类(主要在遍历时候,确定游标起始位置和结束位置)
  7. CursorIterator : 默认实现游标的迭代器
  8. 游标不能多次获取迭代器(有且仅有一次)
  9. 这个核心方法fetchNextObjectFromDatabase(), 获取转换后实体类(这个实体类是一个泛型T表示)
  10. 游标有四个状态 创建、打开、关闭、已被消费

你可能感兴趣的:(mybatis源码,MyBatis源码)