public abstract class AbstractPageProcess extends AbstractJob { protected int page_size = 1000; public final void execute() { long count = enhanceCount(); if (count > 0) { //计算总页数(不包含余数页) long totalPage = count / page_size; //第一页 long page_num = 1; //最后一页数据 long yushu = count % page_size; String sql = pageSql(); while (totalPage-- != 0) { List<Record> thisList = Db.find(sql, (page_num - 1) * page_size, page_size); process(thisList); page_num++; } if (yushu > 0) { List<Record> yushuList = Db.find(sql, (page_num - 1) * page_size, yushu); process(yushuList); } } } // 防止 NullRuntimeException protected long enhanceCount() { return Optional.of(count()).orElse(0L); } // 分页sql protected abstract String pageSql(); // 统计数量 protected abstract Long count(); // 数据处理 protected abstract void process(List<Record> list); // 任务处理 protected void task() { execute(); } }
使用示例:
public class DemoJob extends AbstractPageProcess { @Override protected String pageSql() { return " select * from test limit ?,? "; } @Override protected Long count() { return Db.queryLong(" select count(*) from test "); } @Override protected void process(List<Record> list) { if (list != null && list.size() > 0) { // ... } } }