【Mybatis报错】attempted to return null from a method with a primitive return type (int).

时间:2025-02-18 08:00:18

错误产生的场景

  • dao层接口如下
int getResourceDataNumsByTitle(String title);
  • 中sql语句如下
<select  parameterType="" resultType="">
        SELECT * FROM t_resourceData where title = #{title}
</select>
  • Service层
for(ResourceData r : resourceDatas){
                if(!(getResourceDataNumsByTitle(()) > 0)){
                    (r);
                    (()+"已插入");
     }
}
  • 报错如下
: Mapper method ' attempted 
to return null from a method with a primitive return type (int).
	at (:93)
	at (:59)
	at .$(Unknown Source)
	at (:39)
	at (:23)
	at (:105)
	at .invoke0(Native Method)
	at (:62)
	at (:43)
	at (:498)
	at $(:50)
	at (:12)
	at (:47)
	at (:17)
	at .(:74)
	at .(:84)
	at .(:75)
	at .(:86)
	at .(:84)
	at (:325)
	at .junit4.(:251)
	at .junit4.(:97)
	at $(:290)
	at $(:71)
	at (:288)
	at $000(:58)
	at $(:268)
	at .(:61)
	at .(:70)
	at (:363)
	at .junit4.(:190)
	at (:137)
	at .junit4.(:68)
	at $(:47)
	at (:242)
	at (:70)
0
2019-04-12 20:30:00.171  INFO 10648 --- [       Thread-2]   : Shutting down ExecutorService 'applicationTaskExecutor'
2019-04-12 20:30:00.177  INFO 10648 --- [       Thread-2]    : {dataSource-1} closed

Process finished with exit code 0

错误原因

  • 分析

本次报错的原因在于sql语句未查询到数据,返回为null。而我们定义的dao层方法是返回为int,就会出现如下这样的提示:
return null from a method with a primitive return type (int).(试图从具有原始返回类型(int)的方法返回null)
Ingeter是int的包装类,int的初值为0,Ingeter的初值为null

  • 解决方式

将dao层的返回类型改为Integer即可。