MyBatis Cursor with Spring Boot

二次信任 提交于 2020-06-29 06:55:25

问题


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

Mapper:

@Mapper
@Repository
interface UserMapper {

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

Consumer:

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

Am I missing something?


回答1:


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

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.

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



来源:https://stackoverflow.com/questions/51655126/mybatis-cursor-with-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!