使用MyBatis查詢 返回類型為int,但是當查詢結果為空NULL,報異常的解決方法


使用MyBatis查詢 返回類型為int,但是當查詢結果為空NULL,會報異常。

例如:

  <select id="getPersonRecordId" parameterType="java.lang.String" resultType="int">
    select role_id
    from p_person_role
    where stffe_id = #{stffeId,jdbcType=VARCHAR}
  </select>

當記錄不存在時會報以下錯誤

Servlet.service() for servlet [springDispatcherServlet] in context with path [/xxxx] threw exception [Request processing failed; 
nested exception is org.apache.ibatis.binding.BindingException: Mapper method 'com.xxx.PersonRoleRelationMapper.getPersonRecordno attempted to return null from a method with a primitive return type (int).] 
with root cause org.apache.ibatis.binding.BindingException: Mapper method 'com.xxx.PPersonRoleRelationMapper.getPersonRecordno attempted to return null from a method with a primitive return type (int).

若遇到該問題,可使用MySQL的IFNULL函數和MAX函數,將返回的NULL值轉換為0。例如,可將上述SQL語句改為:

select IFFULL(MAX(role_id),0) AS role_id  from  p_person_role where  stffe_id = #{stffeId,jdbcType=VARCHAR}

 


 

在SQLSERVER中我們可以這樣寫:
select ISNULL(max(data),0) ...


 

在Oracle中我們可以這樣寫:
select NVL(max(data),0) ...


 

對於所有數據庫適用的方法可以這樣寫:
select COALESCE(max(data),0) ...


 

當然以上max也可以用sum函數代替。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM