Spring Boot 整合 MyBatis 出现 'Mapper method attempted to return null from a method with a primitive return type' 错误的解决方法
在使用 Spring Boot 整合 MyBatis 时,可能会遇到如下错误:
'Mapper method 'org.example.dao.AdminDao.deletById attempted to return null from a method with a primitive return type (int).'
根据报错信息,问题出在 AdminDao 的 deletById 方法上,该方法返回类型为 int(原始类型),但是实际返回了 null。
错误原因
Java 中的原始类型(如 int、float、double 等)不能为 null,而 MyBatis 在执行 Mapper 方法时,如果返回值为 null,则会抛出该错误。
解决方法
-
修改 AdminDao 的 deletById 方法,确保不返回 null 值。例如,可以在方法中添加一个默认返回值,或者在执行 SQL 语句后,判断返回结果是否为空,如果为空,则返回一个默认值。
-
将 AdminDao 的 deletById 方法的返回类型改为 Integer(包装类型)。包装类型允许返回 null 值。
代码示例
// 方法 1:添加默认返回值
public int deletById(Integer id) {
int result = adminMapper.deletById(id);
if (result == 0) {
return -1; // 返回一个默认值
}
return result;
}
// 方法 2:将返回类型改为 Integer
public Integer deletById(Integer id) {
return adminMapper.deletById(id);
}
总结
在 Spring Boot 整合 MyBatis 时,如果遇到 'Mapper method attempted to return null from a method with a primitive return type' 错误,请检查 Mapper 方法的返回值类型,确保不返回 null 值,或者将返回类型改为包装类型。
原文地址: https://www.cveoy.top/t/topic/o7eh 著作权归作者所有。请勿转载和采集!