import lombok.extern.slf4j.Slf4j;
import java.util.List;
@Slf4j
public final class BatchOperator {
private BatchOperator() {
}
/**
* 批量操作
*
* @param pageSize
* @param list
* @param callback
* @param <T>
* @return
*/
public static <T> int operate(int pageSize, List<T> list, Callback callback) {
int total = list.size();
int pages = total <= pageSize ? 1 : total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
try {
for (int i = 0; i < pages; i++) {
if ((i + 1) * pageSize <= total) {
callback.execute(list.subList(i * pageSize, (i + 1) * pageSize));
} else {
callback.execute(list.subList(i * pageSize, total));
}
}
return 1;
} catch (Exception e) {
log.error("操作出错:{}", e);
}
return 0;
}
public static interface Callback<T> {
void execute(List<T> list);
}
}
工作中看别人写的代码。。。l留个记录
用法: 1000条一次复制
if(CollUtil.isNotEmpty(updateList)) { long start = System.currentTimeMillis(); BatchOperator.operate(1000, updateList, (itemList) -> { offipoStockIpoInfoMapper.batchUpdate(itemList); }); log.info("分批更新完成,耗时:{}", (System.currentTimeMillis() - start) / 1000 ); }