今天发现测试环境报出来一个数据库相关的错误 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)
public long getUserId(String userName) {
Long userId = userMapper.getUserId(userName);
if (userId == null) {
return 0;
}
return userId;
}
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 ''