mybatis批量插入

一、定义DBExec

import java.util.List;


public abstract class DBExec {
    public abstract void operate(List list);
}

二、定义BatchDBService

public interface BatchDBService {
    void exec(int batchSize, List list, DBExec dbExec);
}

三、实现BatchDBService

@Service
public class BatchDBImpl implements BatchDBService {
    @Override
    public void exec(int batchSize, List list, DBExec 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 batchInsertList = new ArrayList<>();
                for (int i = j * init; i < (j + 1) * init && i < list.size(); i++) {
                    batchInsertList.add(list.get(i));
                }
                dbExec.operate(batchInsertList);
            }

        }

    }
}

四、使用

   BatchDBService batchDBService = new BatchDBImpl();
        DBExec saveDBExec = new DBExec() {
            @Override
            public void operate(List list) {
                testDao.batchInsert(list);
            }
        };
        batchDBService.exec(2000, testList, saveDBExec);

你可能感兴趣的:(mybatis,批量插入)