MyBatis 流式查询、 快速分页
概念
** 流式查询 ** 指的是查询成功后不是返回一个集合而是返回一个迭代器, 应用每次从迭代器取一条查询结果。 流式查询的好处是能够降低内存使用。
如果不采用流式查询, 想要从数据库取 1000 万条记录而又没有足够的内存时, 就不得不分页查询, 而分页查询效率取决于表设计, 如果设计的不好, 就无法执行高效的分页查询。 因此流式查询是一个数据库访问框架必须具备的功能。
接口
流式查询的过程当中, 数据库连接是保持打开状态的, 因此要注意的是: 执行一个流式查询后, 数据库访问框架就不负责关闭数据库连接了, 需要应用在取完数据后自己关闭。# 流式查询接口
MyBatis 提供了一个叫 org.apache.ibatis.cursor.Cursor 的接口类用于流式查询
package org.apache.ibatis.cursor;
import java.io.Closeable;
/**
* 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 / guillaume@dropinocean.com
*/
public interface Cursor<T> extends Closeable, Iterable<T> {
/**
* @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();
/**
* 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();
}
Cursor继承了 java.io.Closeable 和 java.lang.Iterable 接口ÿ