mybatis流式查询数据

  • Post author:
  • Post category:其他


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;  
    });  
} 



版权声明:本文为qq_34495753原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。