当查询百万级或千万级大数据量的时候,MyBatis 普通查询(一次性查询出所有数据,将查询后的结果集全部塞给客户端)可能会 OOM(OutOfMemoryError)。使用游标可以节省内存消耗,不需要一次性取出所有数据,只需一次查询指定 fetchSize 的数据,直到把数据全部处理完。以下是项目中的demo。
数据库表 tbl_mgm_menu 中已构造出大量数据(如何构造大量测试数据,见上一篇博客《MySQL - 使用存储过程快速制造大量测试数据》),springboot + mybatis 项目(见《SpringBoot 整合 MyBatis 配置多数据源操作MySQL数据库》),查询该表中的全部数据集,DAO 层接口定义如下。
package com.test.svc.dao.mgm;
import com.test.svc.model.mgm.Menu;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.mapping.ResultSetType;
import java.util.List;
public interface MenuMapper {
// @Options 标签配置可缺省
// @Options(resultSetType = ResultSetType.FORWARD_ONLY, fetchSize = 5)
List<Menu> selectAll();
}
mapper 查询全部语句。
<select id="selectAll" resultMap="BaseResultMap" fetchSize="-2147483648">
select
<include refid="Base_Column_List" />
from tbl_mgm_menu
</select>
有的博客说 mybatis jdbcUrl 需要开启如下配置(笔者测试过程中,加不加该配置都可以)
useCursorFetch=true
service 层调用示例。
package com.test.svc.service;
import com.test.svc.ApplicationContextHelper;
import com.test.svc.dao.mgm.MenuMapper;
import com.test.svc.model.mgm.Menu;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* 综合查询类
*/
@Service
@Slf4j
public class QueryService {
@Resource
private MenuMapper menuMapper;
/**
* 游标查询全量列表
*
* @return 全部菜单列表
*/
public List<Menu> listMenuByCursor() {
long start = System.currentTimeMillis();
List<Menu> menuList = new ArrayList<>();
try {
SqlSessionFactory mgmSqlSessionFactory = (SqlSessionFactory) ApplicationContextHelper.applicationContext.getBean("mgmSqlSessionFactory");
SqlSession sqlSession = mgmSqlSessionFactory.openSession();
Cursor<Menu> menus = sqlSession.selectCursor("com.test.svc.dao.mgm.MenuMapper.selectAll");
Iterator iter = menus.iterator();
while (iter.hasNext()) {
Menu menu = (Menu) iter.next();
menuList.add(menu);
}
menus.close();
sqlSession.close();
} catch (IOException e) {
log.error("游标查询菜单列表出现异常", e);
}
long end = System.currentTimeMillis();
log.info("游标查询菜单条数:[{}],耗时:[{}]ms", menuList.size(), (end - start));
return menuList;
}
}