Heycm

Heycm

MyBatis流式查询

2023-03-14
MyBatis流式查询

MySQL的

写法一

service

    @Resource(name = UserDataSourceConfig.SQL_SESSION_FACTORY_BEAN)
    private SqlSessionFactory userSqlSessionFactory;

    public void demo() {
        log.info("流式查询:开始...");
        final long l = System.currentTimeMillis();
        AtomicInteger i = new AtomicInteger();
        try (
                final SqlSession sqlSession = userSqlSessionFactory.openSession();
                final Cursor<UserProfile> cursor = sqlSession.getMapper(UserProfileMapper.class).cursorUser()
        ) {
            cursor.forEach(user -> {
                i.getAndIncrement();
                log.info("用户: {}", user.getUserId());
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("流式查询:共 {} 行, 耗时: {}ms", i, (System.currentTimeMillis() - l));
    }

mapper

Cursor<UserProfile> cursorUser();

xml

<select id="cursorUser" resultType="com.xxx.UserProfile" resultSetType="FORWARD_ONLY" fetchSize="-2147483648">
      SELECT user_id FROM user_profile
</select>

写法二

service

    @Resource
    private UserProfileMapper userProfileMapper;

    public void demo2() {
        log.info("流式查询:开始...");
        final long l = System.currentTimeMillis();
        AtomicInteger i = new AtomicInteger();
        userProfileMapper.selectForwardOnly(resultContext -> {
            i.getAndIncrement();
            final UserProfile user = resultContext.getResultObject();
            log.info("用户: {}", user.getUserId());
        });
        log.info("流式查询:共 {} 行, 耗时: {}ms", i, (System.currentTimeMillis() - l));
    }

mapper

void selectForwardOnly(ResultHandler<UserProfile> resultHandler);

xml

<select id="selectForwardOnly" resultType="com.xxx.UserProfile" resultSetType="FORWARD_ONLY" fetchSize="-2147483648">
      SELECT user_id FROM user_profile
</select>