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的区别

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

@Select("select id from user where name = #{userName} and status = 1")
long getInitialPolicyIdByVer(@Param("userName") String name);

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

Long a = null;
long b = a;

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

三、解决方案

  • 方案一:

我们将返回类型修改为Long就可以了,并在对应的Service层做相应的判断就可以了

public long getUserId(String userName) {
Long userId = userMapper.getUserId(userName);
if (userId == null) {
return 0;
}
return userId;
}
  • 方案二:

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

select ifnull(id,0) from user where name = 'test' and status = 1;
select case id when null then 0 end from user where name = 'test' and status = 1;

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

猜你喜欢

转载自www.cnblogs.com/lingyejun/p/8991794.html