1. 程式人生 > >使用MyBatis查詢 返回類型為int,但是當查詢結果為空NULL,報異常的解決方法

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

ati bin turn apache led .get urn bsp process

使用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(sum(data),0) ...


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


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


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

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