有时候想把mybaties的查询做分页,联合多线程使用。
欲实现分页,需做一下步骤:
1. pom加入 pageHelper的依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.4</version>
</dependency>
2. 在 mybaties的配置文件中加入分页配置
<configuration>
<!-- 加载数据库属性文件 -->
<properties resource="db.properties"/>
<!-- 配置分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
<!-- 省略其他 -->
</configuration>
3.执行操作的地儿,加入startPage
// ...
int times = (int) Math.ceil(1.0 * totalWarehouses / PAGE_SIZE);
for (int i = 1; i <= times; i++) {
PageHelper.startPage(i, PAGE_SIZE); // 分页
List<LogMetaBean> logMetaList = mapper.selectLogIdFromLogMeta();
ExcutorThread thread = new ExcutorThread(logMetaList, logMetaWarehousesCost, logMetaMap);
fixedThreadPool.execute(thread);
}
// ...
代码中ExcutorThread是一个实现Runnerable接口的线程,fixedThreadPool是一个定长线程池。注意在结合线程池操作的时候,应先分页,执行sql操作得到需要的数据,传递给子线程处理。不能将页数 i 传递到子线程,在子线程里进行startPage
参考文献
https://blog.youkuaiyun.com/eson_15/article/details/52270046