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 接口ÿ

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值