zoukankan      html  css  js  c++  java
  • MyBatis 流式查询

    基本概念

    流式查询指的是查询成功后不是返回一个集合而是返回一个迭代器,应用每次从迭代器取一条查询结果。流式查询的好处是能够降低内存使用。

    如果没有流式查询,我们想要从数据库取 1000 万条记录而又没有足够的内存时,就不得不分页查询,而分页查询效率取决于表设计,如果设计的不好,就无法执行高效的分页查询。因此流式查询是一个数据库访问框架必须具备的功能。

    流式查询的过程当中,数据库连接是保持打开状态的,因此要注意的是:执行一个流式查询后,数据库访问框架就不负责关闭数据库连接了,需要应用在取完数据后自己关闭。

     

    MyBatis 流式查询接口

    MyBatis 提供了一个叫 org.apache.ibatis.cursor.Cursor 的接口类用于流式查询,这个接口继承了 java.io.Closeable 和 java.lang.Iterable 接口,由此可知:

    1、Cursor 是可关闭的;

    2、Cursor 是可遍历的。

    除此之外,Cursor 还提供了三个方法:

    1、isOpen():用于在取数据之前判断 Cursor 对象是否是打开状态。只有当打开时 Cursor 才能取数据;

    2、isConsumed():用于判断查询结果是否全部取完。

    3、getCurrentIndex():返回已经获取了多少条数据

     

    示例

    @RestController
    @Api(tags = "XcLogController")
    @RequestMapping("/xc_log")
    @Slf4j
    public class XcLogController {
    
        @Resource
        private XcLogMapper xcLogMapper;
    
        @ApiOperation("流式查询")
        @RequestMapping(value = "/streamQuery", method = RequestMethod.GET)
        @Transactional
        public List<XcLog> streamQuery(XcLog xcLog) {
            log.info("/xc_log/streamQuery");
            // return xcLogMapper.streamQuery(xcLog);
    
            try (Cursor<XcLog> cursor = xcLogMapper.streamQuery(xcLog)) {
                cursor.forEach(t -> {
                    // log.info(t.toString());
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    
    
    }
    public interface XcLogMapper {
    
        Cursor<XcLog> streamQuery(XcLog xcLog);
    
    }
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.xc.xcspringboot.mapper.xcLog.XcLogMapper">
    
        <resultMap id="XcLogResultMap" type="com.xc.xcspringboot.model.xcLog.XcLog">
            <result column="id" property="id"/>
            <result column="create_time" property="createTime"/>
            <result column="update_time" property="updateTime"/>
            <result column="is_delete" property="isDelete"/>
        </resultMap>
    
        <select id="streamQuery" resultMap="XcLogResultMap" fetchSize="100">
            select *
            from xc_log
        </select>
    
    
    </mapper>

    参考文章:https://segmentfault.com/a/1190000022478915

  • 相关阅读:
    C语言中结构体变量之间赋值
    ZOJ
    【微服务干货系列】使用微服务架构之前,你必须知道的
    使用heartbeat+monit实现主备双热备份系统
    rsync 3.1.1源代码编译安装配置
    oracle 11g GRID 中 关于 OLR 须要知道的一些内容
    字母游戏
    移动开发人员应避免的 4 大陷阱
    看看这个经常被0基础程序猿弄不懂的 “事件”
    【剑指offer】和为定值的连续正数序列
  • 原文地址:https://www.cnblogs.com/ooo0/p/14167883.html
Copyright © 2011-2022 走看看