带有 Spring Boot 的 MyBatis 游标 [英] MyBatis Cursor with Spring Boot

查看:494
本文介绍了带有 Spring Boot 的 MyBatis 游标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有 Spring Boot 的 MyBatis Cursor 来迭代一个大型查询:

I'm trying to use a MyBatis Cursor with Spring Boot to iterate a large query:

映射器:

@Mapper
@Repository
interface UserMapper {

    @Select("SELECT * FROM huge_user_table")
    Cursor<User> getUsers();

消费者:

@Component
public class UserProcessor {
    @Autowired private UserMapper userMapper;

    public boolean process() throws IOException {
        Cursor<User> users = userMapper.getUsers();
        //users.isOpen() == false
        for (User user : users) {
            //Never iterates
            System.out.println(user.getId());
        }

当我将光标取回时,尽管它已关闭,但没有返回任何记录.

When I get my cursor back though it is closed, with no records returned.

我错过了什么吗?

推荐答案

最有可能的问题是您尝试在事务之外使用 Cursor.这不受支持.

Most probably the problem is that you try to use Cursor outside of transaction. This is not supported.

Cursor 基本上是 JDBC ResultSet 的包装器.为了从 Cursor 获取值,应该打开底层的 ResultSet.如果您在整个循环期间都没有事务,那么 spring 将在执行查询时打开连接(在您的情况下是 getUsers 方法的持续时间).方法完成后,连接关闭,因此 Cursor 使用的 ResultSet 也关闭.

Cursor is basically a wrapper around JDBC ResultSet. In order to fetch values from Cursor the underlying ResultSet should be opened. If you do not have a transaction for the whole duration of the loop then spring will open the connection when the query is executed (in your case for the duration of getUsers method). After the method is finished the connection is closed and therefore the ResultSet used by Cursor is closed as well.

@Transactional 添加到 process,这应该可以解决问题.

Add @Transactional to process and this should fix the issue.

这篇关于带有 Spring Boot 的 MyBatis 游标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆