一、场景和背景
工具:mybatis + pgsql
dao代码:
int selectMaxAgeBySex(String sex); 查询性别是女生的最大年龄
sql:
<select id = "selectMaxAgeBySex" resultType="int">
select max(age) from user where sex = '女';
</select>
二、错误原因
如果数据表user中没有性别是女的用户数据,那么pgsql
返回的函数max值是null,此时把null赋值给了resultType=“int”,报错信息:
mapper method attempted to return null from a method with a primitive return type (int)
三、解决
pgsql数据库的max返回值有两种,null和数值。
当返回的数据是nu l l空对象时,即意味着把null赋值给int。如果用程序实现将会报空指针异常,例如:
package com.test.boke;
public class TestJava {
public static void main(String[] args) {
Integer integer = null;
int num = integer;
System.out.println("num = " + num);
}
}
console输出:
Exception in thread "main"
java.lang.NullPointerException
at com.test.boke.TestJava.main
(TestJava.java:6)
所以不可以使用resultType="int"
作为返回类型。正确的代码是:
dao代码:
Integer selectMaxAgeBySex(String sex); 查询性别是女生的最大年龄
sql:
<select id = "selectMaxAgeBySex" resultType="java.lang.Integer">
select max(age) from user where sex = '女';
</select>