在SpringBoot+Mybatis系统中,涉及到SQL查询数据量较大的场景,将所有数据一次查出存放到内存里,会造成较大的系统负担。通常有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方法对查询数据进行逐个处理。