mapper method attempted to return null from a method with a primitive return type (int)

一、场景和背景

工具: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>
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值