【mysql】查詢返回int數據爲空時處理

使用MyBatis查詢,返回類型爲int,但是當查詢結果爲空null,出現異常

如代碼中xml文件查詢語句

<select id="getGenerateStatus" resultType="java.lang.Integer">
      select 
      		is_generating
      from 
      		report_info 
      where 
      		task_id = #{taskId}
</select>

當未查詢到任何數據返回null時,程序報錯

[2020-07-02 19:16:39.496][http-nio-3100-exec-2][ERROR]
[com.xxx.exception.ExceptionHandlers:43] 發生空指針異常!原因是:
java.lang.NullPointerException: null

在mysql中可以使用IFNULL函數和MAX函數,將返回的NULL值轉換爲0
SQL語句可修改爲:

<select id="getGenerateStatus" resultType="java.lang.Integer">
     select 
     		IFNULL(MAX(is_generating),0) as is_generating 
     from 
     		report_info 
     where 
     		task_id = #{taskId}
</select>

sum也可以使用max函數代替

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