MyBatis-Plus 的 'saveBatch' 方法在批量插入数据时,如果出现错误会抛出 'BatchInsertException' 异常,该异常会包含一个 'cause' 字段,其中记录了具体哪条数据插入失败。

可以通过捕获 'BatchInsertException' 异常,然后通过 'cause' 字段获取具体的失败数据。

以下是一个示例代码:

try {
    List<User> userList = new ArrayList<>();
    // 添加要插入的数据到userList中

    userService.saveBatch(userList);
} catch (BatchInsertException e) {
    Throwable cause = e.getCause();
    if (cause instanceof SQLException) {
        SQLException sqlException = (SQLException) cause;
        int index = sqlException.getErrorCode() - 1;  // 获取失败数据在列表中的索引,注意索引从0开始
        User failedUser = userList.get(index);
        // 处理失败数据 failedUser
        System.out.println('数据插入失败:' + failedUser);
    }
}

在上述代码中,如果 'saveBatch' 方法出现错误,会捕获 'BatchInsertException' 异常。然后通过 'getCause' 方法获取具体的失败原因,判断是否为 'SQLException' 类型。如果是,则可以通过 'getErrorCode' 方法获取到失败数据所在的索引,然后根据索引从列表中获取到具体的失败数据。

MyBatis-Plus saveBatch 方法批量插入失败数据定位

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

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