MyBatis流式查询

本文介绍了MyBatis的流式查询,这是一种通过返回Cursor迭代器实现的数据查询方式,可以有效减少内存占用。流式查询需要注意保持数据库连接开放并手动关闭。在Spring中,可以使用TransactionTemplate进行事务控制,或者利用@Transactional注解来管理事务。示例代码展示了如何在实际应用中使用流式查询。
摘要由CSDN通过智能技术生成

转自:

Mybatis流式查询

下文笔者讲述Mybatis流式查询的相关简介说明,如下所示

Mybatis流式查询简介

流式查询简介:
   我们将MyBatis返回数据为一个迭代器,这种查询模式称之为“流式查询”
流式查询的返回值:
   使用迭代器逐条的遍历数据

流式查询注意事项:
   流式查询过程中
    数据库连接必须保持一直打开
     并且执行完查询后需要手动的关闭数据库连接

MyBatis流式查询接口

MyBatis提供了
org.apache.ibatis.cursor.Cursor 的接口类用于流式查询
此接口继承了 java.io.Closeable 和 java.lang.Iterable 接口
所以Cursor 是可关闭/遍历的。

Cursor常见的方法

方法名备注
isOpen()用于在取数据之前判断 Cursor 对象是否是打开状态,只有当打开时 Cursor 才能取数据
isConsumed()用于判断查询结果是否全部取完
getCurrentIndex()返回已经获取了多少条数据

使用 Cursor 流式接口

 @Mapper
public interface TestMapper {
   @Select("select * from test limit #{limit}")
   Cursor<Test> scan(@Param("limit") int limit);
}


@GetMapping("test/1/{limit}")
public void testFun(@PathVariable("limit") int limit) throws Exception {
   try (
       SqlSession sqlSession = sqlSessionFactory.openSession();  // 1
       Cursor<Test> cursor =
             sqlSession.getMapper(TestMapper.class).scan(limit)   // 2
  ) {
       cursor.forEach(Test -> { });
  }
}
上述代码1位置
  开启一个SqlSession(实际上也代表了一个数据库连接)
  并保证它最后能关闭
  2位置
  使用 SqlSession 来获得 Mapper 对象
  采用以上模式能保证得到的 Cursor 对象是打开状态的。

2.事务控制 TransactionTemplate
在 Spring 中,可以用 TransactionTemplate 来执行一个数据库事务 

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

   transactionTemplate.execute(status -> {               // 2
       try (Cursor<Test> cursor = TestMapper.scan(limit)) {
           cursor.forEach(test -> { });
      } catch (IOException e) {
           e.printStackTrace();
      }
       return null;
  });
}
上面的代码中1处创建了一个 TransactionTemplate 对象
2处执行数据库事务
而数据库事务的内容则是调用Mapper对象的流式查询
注意这里的 Mapper 对象无需通过 SqlSession 创建

事务控制 @Transactional 注解
这个本质上和方案二一样,代码如下:

@GetMapping("test/3/{limit}")
@Transactional
public void test(@PathVariable("limit") int limit) throws Exception {
   try (Cursor<Test> cursor = TestMapper.scan(limit)) {
       cursor.forEach(test -> { });
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值