你可以创建一个名为BatchUtils的工具类,来实现MyBatis的批处理操作。以下是一个简单的示例代码:

public class BatchUtils {
    private static final int BATCH_SIZE = 100;

    public static void executeBatch(SqlSession sqlSession, String statement, List<Object> parameterList) {
        int size = parameterList.size();
        int batchCount = (size + BATCH_SIZE - 1) / BATCH_SIZE;

        for (int i = 0; i < batchCount; i++) {
            int fromIndex = i * BATCH_SIZE;
            int toIndex = Math.min((i + 1) * BATCH_SIZE, size);
            List<Object> subList = parameterList.subList(fromIndex, toIndex);
            sqlSession.insert(statement, subList);
        }

        sqlSession.commit();
    }
}

使用该工具类,你可以将你的代码改写如下:

public Result add(CheckGroup checkGroup, Integer[] checkitemIds) {
    try {
        checkGroupMapper.insert(checkGroup);
        if (checkitemIds.length <= 0) {
            return new Result(false, MessageConstant.ADD_CHECKGROUP_FAIL, null);
        }

        try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) {
            CheckItemAndGroupMapper mapper = sqlSession.getMapper(CheckItemAndGroupMapper.class);
            List<Object> parameterList = new ArrayList<>();

            for (int index = 0; index < checkitemIds.length; index++) {
                parameterList.add(new Object[] { checkitemIds[index], checkGroup.getId() });

                if ((index + 1) % BatchUtils.BATCH_SIZE == 0 || index == checkitemIds.length - 1) {
                    BatchUtils.executeBatch(sqlSession, "insert", parameterList);
                    parameterList.clear();
                }
            }

            sqlSession.commit();
        }
    } catch (Exception e) {
        return new Result(false, MessageConstant.ADD_CHECKGROUP_FAIL, null);
    }

    return new Result(true, MessageConstant.ADD_CHECKGROUP_SUCCESS, null);
}

请注意,这只是一个简单示例,具体的实现可能需要根据你的代码和需求做一些调整

private int Batch=2;overrideTransactionalpublic Result addCheckGroup checkGroupInteger checkitemIds try checkGroupMapperinsertcheckGroup;if checkitemIdslength=0return new Result flag falseMessageConst

原文地址: http://www.cveoy.top/t/topic/iXA6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录