偶然碰到这样一个错,仔细找原因,发现了一个自己坏的编码习惯。
return null from a method with a primitive return type (int).
SQL 对某个字段(单独一个)按条件查询,数据库字段定义成smallint
。
某种条件下,查不到,也就是查询结果是 Null:
如果符合判断条件,会返回如下:
然后项目中 Mybatis xml 返回值用 resultType="java.lang.Integer"
接收。
到这一步是没问题的,因为 Integer 是对象,能接收 Null。
但 Mapper 方法中却返回 int 类型的数据。
int getInt(String id);
如果不是 Null,这里没问题,因为从 Integer 到 int 会发生自动拆箱。
但这里刚好是 Null ,拆箱会出现编译错误,基本数据类型不能接收 Null。
还是得养成严谨的习惯:
Integer getInt(String id);
调用这个函数方法一样得用 Integer 接收,不然又会自动拆箱,有报空指针的可能。
Integer integer = getInt(2);
那使用这个 integer 呢,要用方法 intValue 转换成 int 吗?
其实无所谓,看怎么使用,因为 Interger 是对象,有一些 int 没有的方法,int 只能做加减乘除。但使用前要对 integer 做判空处理。
本文由老郭种树原创,转载请注明:https://guozh.net/return-null-from-a-method-with-a-primitive-return-type-int/