mybatis 分批次手动提交事务

@Autowired
private SqlSessionFactory sqlSessionFactory;

public boolean saveOrUpdateStockBatch(List entityList, int batchSize, StockOperationTypeEnum operationTypeEnum) {
        // 此种提交方法,会导致新增后主键无法回显,暂时废弃
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        SaleStockDAO mapper = session.getMapper(SaleStockDAO.class);
        try {
            if (entityList.size() <= batchSize) {
                executeStock(operationTypeEnum, mapper, entityList);
            } else {
                List list = Lists.newArrayList();
                for (int i = 0; i < entityList.size(); i++) {
                    list.add(entityList.get(i));
                    if (i >= 1 && i % batchSize == 0) {
                        executeStock(operationTypeEnum, mapper, list);
                        session.commit();
                        session.clearCache();
                        list.clear();
                    }
                }
                if (CollectionUtil.isNotEmpty(list)) {
                    executeStock(operationTypeEnum, mapper, list);
                }
            }
            session.commit();
            session.clearCache();
        } catch (Exception e) {
            logger.error(CharConstant.ERROR, e);
            session.rollback();
            ExceptionUtils.throwServiceException(ErrorCodeConstant.STOCK_UPDATE_FAIL);
        } finally {
            session.close();
        }
        return true;


private void executeStock(StockOperationTypeEnum operationTypeEnum, SaleStockDAO mapper, List list) {
    mapper.batchInsertIgnore(list);
}

 

你可能感兴趣的:(开发工具)