今天学习一下cursor包的下源码,了解mybatis大致游标实现
/**
* 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();
}
/**
* 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");
}
}
}