天天看點

使用Mybatis報錯:java.lang.NullPointerException排查方案1 開啟列印SQL語句的配置2 檢查SQL裡的字段3 檢查資料庫的字元編碼4 檢查Mapper是否注入成功5 List All elements are null導緻NullPointerException

nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: java.lang.NullPointerException
### The error may involve com.hzgroup.switchproject.dao.inter.mysql.DistributionBookingDao.updateByPrimaryKeySelective-Inline
### The error occurred while setting parameters
### SQL: update xxx
### Cause: java.lang.NullPointerException      
使用Mybatis報錯:java.lang.NullPointerException排查方案1 開啟列印SQL語句的配置2 檢查SQL裡的字段3 檢查資料庫的字元編碼4 檢查Mapper是否注入成功5 List All elements are null導緻NullPointerException

1 開啟列印SQL語句的配置

因為是通過MyBatis 連接配接資料庫,是以需要檢視SQL的執行語句

Spring+Mybatis在控制台輸出SQL的最簡單方法:

application.yml

檔案中添加:

  • logging.level.Mapper所在包=debug
  • 使用Mybatis報錯:java.lang.NullPointerException排查方案1 開啟列印SQL語句的配置2 檢查SQL裡的字段3 檢查資料庫的字元編碼4 檢查Mapper是否注入成功5 List All elements are null導緻NullPointerException

2 檢查SQL裡的字段

SQL裡的字型要與實體類的成員變量相對應,大小寫也要注意。

注意區分屬性ResutlMap和ResultType的使用,别混了。

3 檢查資料庫的字元編碼

資料庫、表、字段的字元編碼都應該統一,最好設定成utf8-general_ci

4 檢查Mapper是否注入成功

@Autowire報錯導緻的NullPointerException,雖然報錯,項目運作沒有問題。可是隻有緊挨着@Autowire的一個起作用,下面的都沒有注入成功。這時需要在每一個注入的Mapper中都加上@Autowire。

5 List All elements are null導緻NullPointerException

當List對象顯示 All elements are null時,雖然輸入為[null],但是list.size()=1。不管是list==null,list.isEmpty(),list.size()都無法判斷list是否為空。

可以在執行上面語句時,加上list.remove(null)