org.apache.ibatis.binding.BindingException: Mapper method 'attempted to return null

org.apache.ibatis.binding.BindingException: Mapper method 'attempted to return null from a method with a primitive return type (long).

一、问题描述

今天发现测试环境报出来一个数据库相关的错误 org.apache.ibatis.binding.BindingException: Mapper method 'attempted to return null from a method with a primitive return type (long).

二、问题根源

经过查询后发现,Mybatis 在查询id信息的时候返回类型为long ,没有留意long和Long的区别

  • Long是long的包装类,long是基本数据类型。
  • Long可以为null,但基本类型long则不可以被赋值null。

当在数据库中查询没有查到这条记录,注意这里是根本没有这条记录,所以当然也不会返回id,对于这种情况Mybatis框架返回结果是null

1

2

@Select("select id from user where name = #{userName} and status = 1")

long getInitialPolicyIdByVer(@Param("userName") String name);

用long取承接null当然是不可以的

1

2

Long a = null;

long b = a;

因为会报java.lang.NullPointerException,而框架报出来的就是attempted to return null from a method with a primitive return type (long)

三、解决方案

  • 方案一:将返回类型修改为Long就可以了,并在对应的Service层做相应的判断就可以了

1

2

3

4

5

6

7

public long getUserId(String userName) {

Long userId = userMapper.getUserId(userName);

if (userId == null) {

return 0;

}

return userId;

}

  • 方案二:对于可以查询到记录的,只是在该记录中你需要的字段是null这种情况下,除了上述方法,还可以通过修改sql来解决。

1

2

select ifnull(id,0) from user where name 'test' and status = 1;

select case id when null then end from user where name 'test' and status = 1;

 

但是站在专业的角度一般在设计数据库时,相关字段都会被设置为NOT NULL DEFAULT ''

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值