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 |
|
用long取承接null當然是不可以的
1 2 |
|
因爲會報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 |
|
-
方案二:對於可以查詢到記錄的,只是在該記錄中你需要的字段是null這種情況下,除了上述方法,還可以通過修改sql來解決。
1 2 |
|
但是站在專業的角度一般在設計數據庫時,相關字段都會被設置爲NOT NULL DEFAULT ''