mybatis流式查询数据

mybatis流式查询数据

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

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

简单使用

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

通过controller调运
fooMapper 是 @Autowired

@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  
    }  
} 

SqlSessionFactory 来手工打开数据库连接,将 Controller 方法修改如下实现保持持续链接:

@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执行事务模式,或者加@Transactional 注解

@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;  
    });  
} 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值