Mapper method 'xxx attempted to return null from a method with a primitive return type (int).
1. 异常信息
ERROR default [http-nio-8001-exec-7] [ o.a.c.c.C.[.[.[.[dispatcherServlet] 175 -
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Mapper method 'LocalMapper.averageResponseTime attempted to return null from a method with a primitive return type (int).] with root cause
org.apache.ibatis.binding.BindingException: Mapper method 'LocalMapper.averageResponseTime attempted to return null from a method with a primitive return type (int).
at com.baomidou.mybatisplus.core.override.MybatisMapperMethod.execute(MybatisMapperMethod.java:106)
at com.baomidou.mybatisplus.core.override.MybatisMapperProxy$PlainMethodInvoker.invoke(MybatisMapperProxy.java:148)
at com.baomidou.mybatisplus.core.override.MybatisMapperProxy.invoke(MybatisMapperProxy.java:89)
at com.sun.proxy.$Proxy183.averageResponseTime(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at com.baomidou.dynamic.datasource.aop.DynamicDataSourceAnnotationInterceptor.invoke(DynamicDataSourceAnnotationInterceptor.java:50)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy184.averageResponseTime(Unknown Source)
2. 查看对应的SQL
select
sum( CASE WHEN TIME_OUT IN ( 1 ) THEN 1 ELSE 0 END ) time_out
from order
where ...
再结合异常信息,就可以发现,是因为通过SQL语句查询出来的数据为空,但Mybatis
<select id="averageResponseTime" resultType="java.lang.Integer">
</select>
resultType 限定的类型是 Integer ,所以框架抛了次异常。问题找到了,为了解决此异常,那就再聚合函数sum() 做文章,通过IFNULL() 函数进行为空 补0 就不会出现此异常了。
3. 调整后
<select id="averageResponseTime" resultType="java.lang.Integer">
select
IFNUll(sum( CASE WHEN TIME_OUT IN ( 1 ) THEN 1 ELSE 0 END ),0) time_out
from order
</select>
4. 拓展
通过其他函数 eg: group by 出现为空的情况也可以通过IFNULL() 进行改造