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

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

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

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

    Cursor 提供了三个方法:

    1. isOpen():用于在取数据之前判断 Cursor 对象是否是打开状态。只有当打开时 Cursor 才能取数据;
    2. isConsumed():用于判断查询结果是否全部取完。
    3. getCurrentIndex():返回已经获取了多少条数据

    因为 Cursor 实现了迭代器接口,因此在实际使用当中,从 Cursor 取数据非常简单:

    cursor.forEach(rowObject -> {...});


    ===================》

    构建 Cursor 的过程不简单

    @Mapper
    public interface FooMapper {
        @Select("select * from foo limit #{limit}")
        Cursor<Foo> scan(@Param("limit") int limit);
    }

    @GetMapping("foo/scan/0/{limit}")
    public void scanFoo0(@PathVariable("limit") int limit) throws Exception {
        try (Cursor<Foo> cursor = fooMapper.scan(limit)) { // 1
            cursor.forEach(foo -> {}); // 2
        }
    }

    方法 scan() 是一个非常简单的查询。通过指定 Mapper 方法的返回值为 Cursor 类型,MyBatis 就知道这个查询方法一个流式查询。

    fooMapper 是 @Autowired 进来的。注释 1 处调用 scan 方法,得到 Cursor 对象并保证它能最后关闭;2 处则是从 cursor 中取数据。

    上面的代码看上去没什么问题,但是执行 scanFoo0() 时会报错:

    java.lang.IllegalStateException: A Cursor is already closed.

    这是因为我们前面说了在取数据的过程中需要保持数据库连接,而 Mapper 方法通常在执行完后连接就关闭了,因此 Cusor 也一并关闭了。

    ======》

    方案一:SqlSessionFactory

    @GetMapping("foo/scan/1/{limit}")
    public void scanFoo1(@PathVariable("limit") int limit) throws Exception {
        try (
            SqlSession sqlSession = sqlSessionFactory.openSession(); // 1
            Cursor<Foo> cursor =
                  sqlSession.getMapper(FooMapper.class).scan(limit) // 2
        ) {
            cursor.forEach(foo -> { });
        }
    }

    方案二:TransactionTemplate===(在 Spring 中,我们可以用 TransactionTemplate 来执行一个数据库事务,这个过程中数据库连接同样是打开的)

    @GetMapping("foo/scan/2/{limit}")
    public void scanFoo2(@PathVariable("limit") int limit) throws Exception {
        TransactionTemplate transactionTemplate =
                new TransactionTemplate(transactionManager); // 1

        transactionTemplate.execute(status -> { // 2
            try (Cursor<Foo> cursor = fooMapper.scan(limit)) {
                cursor.forEach(foo -> { });
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        });
    }

    方案三:@Transactional 注解

    @GetMapping("foo/scan/3/{limit}")
    @Transactional
    public void scanFoo3(@PathVariable("limit") int limit) throws Exception {
        try (Cursor<Foo> cursor = fooMapper.scan(limit)) {
            cursor.forEach(foo -> { });
        }
    }

  • 相关阅读:
    微信小程序-rpx
    vue项目页面切换到默认显示顶部
    访问formData的数据
    vue图片懒加载
    react+umi+dva
    switch判断中,case后面跟逻辑表达式出错
    给2020做一个小结
    react+next.js遇到的问题及解决
    域名相关(结构与规范)
    react+antd一边踩坑一边积累
  • 原文地址:https://www.cnblogs.com/KL2016/p/15292624.html
Copyright © 2011-2022 走看看