-
错误日志
java org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 2
-
错误代码示例
int studentNum = studentLackDealService.count( new LambdaQueryWrapper<StudentLackDeal>().eq(StudentLackDeal::getBatchId, batchId) .groupBy(StudentLackDeal::getAdmissionTicket));
-
问题分析
代码看起来没什么问题,是求出groupBy之后的数量,但是此时我们通过生成的sql可以看到:
SELECT COUNT(*) FROM exam_student_lack_deal WHERE del_flag = 0 AND ( batch_id = XXX )
这样查询出来的结果是多行数值:
而mybatis-plus的Count()方法用的是int接收,返回的确是一个list,自然而然就会报错了 -
解决方案
1. 使用 list() 接收处理,.size()获取数量int studentNum = studentLackDealService.list( new LambdaQueryWrapper<StudentLackDeal>().eq(StudentLackDeal::getBatchId, batchId) .groupBy(StudentLackDeal::getAdmissionTicket)).size();
- 去除groupBy 使用DISTINCT关键字去重
int studentNum = studentLackDealService.count( new QueryWrapper<StudentLackDeal>().select("DISTINCT admission_ticket").lambda().eq(StudentLackDeal::getBatchId, batchId));
mybatisplus:Count()方法和groupBy组合使用的报错问题
于 2022-07-01 12:40:45 首次发布