自学内容网 自学内容网

使用MyBatisCursorItemReader实现基于流的大批量数据读取

在SpringBoot+Mybatis系统中,涉及到SQL查询数据量较大的场景,将所有数据一次查出存放到内存里,会造成较大的系统负担。通常有2种方式解决:

  1. 采用分页方式,分多次查询数据并处理
  2. 使用Mybatis提供的MyBatisCursorItemReader,实现基于流的数据读取

这里介绍第二种用法。

原始代码:

    @Override
    public List<ScUserExportListV> exportList(UserListF form) {
        // 总记录数1000w条
        List<ScUserExportListV> userList = baseMapper.exportList(form);
        return userList;
    }
<select id="exportList" resultType="com.yechen.smm.domain.vo.ScUserExportListV">
    select id, intime, name, status, work_experience as workExperience
    from sc_user
    <where>
        <if test="name != null and name != ''">
            and name like concat('%', #{name}, '%')
        </if>
    </where>
</select>

实现方式:

        1、引入 springBatch 依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-batch</artifactId>
</dependency>

        2、修改Service层方法

@Override
public List<ScUserExportListV> exportList(UserListF form) {
// 总记录数1000w条
//        List<ScUserExportListV> userList = baseMapper.exportList(form);

MyBatisCursorItemReader<ScUserExportListV> reader = new MyBatisCursorItemReader<>();
// 查询方法的映射路径
reader.setQueryId("com.yechen.smm.mapper.ScUserMapper.exportList");
reader.setSqlSessionFactory(sqlSessionFactory);
reader.setParameterValues(BeanUtil.beanToMap(form));
try {
reader.open(new ExecutionContext());

while (true) {
ScUserExportListV v = reader.read();
if (v == null) {
break;
}

// todo 对单个 ScUserExportListV 进行业务处理
}
} catch (Exception e) {
e.printStackTrace();
} finally {
reader.close();
}
return Collections.emptyList();
}
reader.open(new ExecutionContext()) 方法会建立一个连接数据库的流,并通过read方法对查询数据进行逐个处理。

 


原文地址:https://blog.csdn.net/qq_38098608/article/details/140637307

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!