一、定义DBExec
java
import java.util.List;
public abstract class DBExec<T> {
public abstract void operate(List<T> list);
}
二、定义BatchDBService
java
public interface BatchDBService<T> {
void exec(int batchSize, List<T> list, DBExec<T> dbExec);
}
三、实现BatchDBService
java
@Service
public class BatchDBImpl<T> implements BatchDBService<T> {
@Override
public void exec(int batchSize, List<T> list, DBExec<T> dbExec) {
if (list != null && list.size() > 0) {
int init = batchSize;// 每隔batchSize条循环一次
int total = list.size();
int cycelTotal = total / init;//获取循环次数
if (total % init != 0) {
cycelTotal += 1;
if (total < init) {
init = total;
}
}
for (int j = 0; j < cycelTotal; j++) {
List<T> batchInsertList = new ArrayList<>();
for (int i = j * init; i < (j + 1) * init && i < list.size(); i++) {
batchInsertList.add(list.get(i));
}
dbExec.operate(batchInsertList);
}
}
}
}
四、使用
java
BatchDBService batchDBService = new BatchDBImpl();
DBExec<TestDO> saveDBExec = new DBExec<TestDO>() {
@Override
public void operate(List<TestDO> list) {
testDao.batchInsert(list);
}
};
batchDBService.exec(2000, testList, saveDBExec);