Home MyBatis查询结果为NULL时报异常的解决方法
Post
Cancel

MyBatis查询结果为NULL时报异常的解决方法

异常信息

1
2
3
org.apache.ibatis.binding.BindingException: Mapper 
method 'com.XXXXX' attempted toreturn null from a 
method with a primitive return type (int).

源代码

1
2
3
4
5
6
7
8
<select id="selectPageviews" resultType="java.lang.Integer" >
  select 
    sum(yc_hobby_pageviews)
  from 
    SCOTT.yc_hobby_course
  where
    yc_hobby_course_user_id = #{yc_hobby_course_user_id}
</select>

Oracle的解决方式

1
select NVL(sum(yc_hobby_pageviews), 0) from ....

MySQL的解决方式

1
select IFFULL(sum(yc_hobby_pageviews), 0) from ....

SQL Server的解决方式 

1
select ISNULL(sum(yc_hobby_pageviews), 0) ...

所有数据库适用

1
select COALESCE(sum(yc_hobby_pageviews), 0) ...
This post is licensed under CC BY 4.0 by the author.