前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >org.apache.ibatis.binding.BindingException: Mapper method 'attempted to return null from a method wi

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

作者头像
翎野君
发布2023-05-12 19:53:00
3200
发布2023-05-12 19:53:00
举报
文章被收录于专栏:翎野君翎野君

一、问题描述

今天发现测试环境报出来一个数据库相关的错误 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

代码语言:javascript
复制
@Select("select id from user where name = #{userName} and status = 1")
long getInitialPolicyIdByVer(@Param("userName") String name);

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

代码语言:javascript
复制
Long a = null;
long b = a;

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

三、解决方案

  • 方案一:将返回类型修改为Long就可以了,并在对应的Service层做相应的判断就可以了
代码语言:javascript
复制
public long getUserId(String userName) {
Long userId = userMapper.getUserId(userName);
if (userId == null) {
return 0;
}
return userId;
}
  • 方案二:对于可以查询到记录的,只是在该记录中你需要的字段是null这种情况下,除了上述方法,还可以通过修改sql来解决。
代码语言:javascript
复制
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 ''

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、问题描述
  • 二、问题根源
  • 三、解决方案
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档