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 ''

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章