• 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

  • 相关阅读:
    BASE64
    2020-2021-1 20201217《信息安全专业导论》第二周学习总结
    师生关系20201217
    2020-2021-1 20201217王菁<<信息安全专业导论>>第一周学习总结
    作业正文(快速浏览教材提出问题)
    自我介绍20201217王菁
    罗马数字转阿拉伯数字(20201225张晓平)
    20201225 张晓平《信息安全专业导论》第三周学习总结
    20201225 张晓平《信息安全专业导论》第二周学习总结
    我期待的师生关系
  • 原文地址:https://www.cnblogs.com/ooo0/p/14167883.html
Copyright © 2020-2023  润新知