mybatis plus 更新的时候返回更新记录的条数
在 MyBatis-Plus 中能否获取更新条数取决于你调用的是Mapper层还是Service层。官方设计有明确区分✅ 正确做法调用BaseMapper返回intBaseMapper的更新方法直接返回受影响的行数与原生 MyBatis 一致。// 1. 注入 Mapper Autowired private DocumentMetadataMapper mapper; // 继承 BaseMapperDocumentMetadata // 2. 调用更新 int affectedRows mapper.updateById(entity); // 或条件更新 int affectedRows mapper.update(null, new LambdaUpdateWrapperDocumentMetadata() .set(DocumentMetadata::getKmStatus, 1) .eq(DocumentMetadata::getId, 100L)); if (affectedRows 0) { log.info(成功更新 {} 条记录, affectedRows); }⚠️ 易混淆点IService返回boolean如果你调用的是Service层继承IService默认返回boolean不返回具体行数Autowired private DocumentMetadataService service; // ❌ 返回 true/false无法获取具体条数 boolean success service.updateById(entity); // 底层实现return baseMapper.updateById(entity) 0;结论需要精确行数时必须绕过 Service直接调用Mapper。 核心配置MySQL 必须加useAffectedRowstrue无论原生 MyBatis 还是 MPMySQL 驱动默认返回的是匹配行数Matched Rows而非实际修改行数。若新旧值相同会返回1导致误判。JDBC URL 必须添加jdbc:mysql://127.0.0.1:3306/your_db?useAffectedRowstruecharacterEncodingutf8serverTimezoneAsia/Shanghai配置状态更新status1→status1更新status1→status2业务影响无useAffectedRows返回1返回1无法区分“数据未变”和“更新成功”有useAffectedRowstrue返回0返回1✅ 精准反映实际变更 常见场景 避坑指南场景现象解决方案乐观锁更新返回0说明Version版本冲突需重试或抛异常逻辑删除干扰updateById不生效检查是否被TableLogic拦截改用mapper.update(null, wrapper)绕过批量更新要行数updateBatchById()返回boolean循环调用mapper.updateById()累加int或写自定义updateXMLPostgreSQL/Oracle返回值行为不同PG 默认返回affected rowsOracle 需注意SQL%ROWCOUNT通常无需额外参数 最佳实践模板public int updateKmStatusWithAudit(Long id, Integer newStatus) { int rows mapper.update(null, new LambdaUpdateWrapperDocumentMetadata() .set(DocumentMetadata::getKmStatus, newStatus) .eq(DocumentMetadata::getId, id)); if (rows 0) { throw new BusinessException(记录不存在或数据未发生变更); } return rows; } 总结要行数 → 用BaseMapper.update*()返回int要布尔值 → 用IService.update*()返回booleanMySQL 必加useAffectedRowstrue否则返回值无业务参考价值乐观锁返回0是正常冲突信号非 SQL 错误如需结合你的具体表结构如含Version、逻辑删除、分库分表优化更新策略可提供 Mapper 代码我为你输出适配方案。