mybatis 返回Integer,Double,String等類型的數據操作
在使用mybatis的過程中會遇到只返回單獨數據類型的問題會用到resultType。
//返回Integer
<select id="getSpeedByLinkId" parameterType="java.lang.String" resultType="Integer">
SELECT speed from dws_tfc_state_speed_link_last_rt where link_id = #{linkId}
</select>
//返回Double類型
<select id="getTravelTimeByLinkId" parameterType="java.lang.String" resultType="Double">
SELECT travel_time from dws_tfc_state_speed_link_last_rt where link_id = #{linkId}
</select>
//返回String 類型
<select id="getSpeedByLinkId" parameterType="java.lang.String" resultType="String">
SELECT speed from dws_tfc_state_speed_link_last_rt where link_id = #{linkId}
</select>
補充知識:mybatis下返回類型為int,結果為null時報tempted to return null from a method with a primitive return type (int).
背景了解:
從mysql數據庫中查詢數據,用Int接收,因為數據庫沒有數據所以返回null,于是運行時報以下錯誤,提取關鍵的信息“attempted to return null from a method with a primitive return type (int).”,翻譯成中文大概意思是“”嘗試從具有基本返回類型(Int)的方法返回null“返回int的方法想要返回null,不符合規(guī)矩。
報錯信息:
xml中的SQL和報錯信息如下:
<select id="getweekalert" resultType="int"> select SUM(alert_sum) as alert_sum from tb_checkresults </select>
2019-06-27 17:39:40,742 ERROR (DirectJDKLog.java:182)- Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Mapper method 'com.chinalife.datacheck.dao.CheckresultDao.getyestodayalert attempted to return null from a method with a primitive return type (int).] with root cause org.apache.ibatis.binding.BindingException: Mapper method 'com.chinalife.datacheck.dao.Checkresul*tDao.getyestodayalert attempted to return null *********************省略以下那些沒用的*********************
解決辦法:
(1)利用mysql的函數ifnull
ifnull函數可以判斷返回值是否為‘null',不為null時直接返回,為null時返回我們指定的‘0'
<select id="getweekalert" resultType="int"> select IFNULL(SUM(alert_sum),0) as alert_sum from tb_checkresults </select>
(2) 將返回類型改為Integer
int是基本數據類型,默認值是0:integer是int的封裝類,是一個類,默認值是null
<select id="getweeekalert" resultType="Integer"> select SUM(alert_sum) as alert_sum from tb_checkresults </select>
找得到,看得懂,明確報錯信息很重要。
解決問題有多種辦法,符合要求的才是最好的。
以上這篇mybatis 返回Integer,Double,String等類型的數據操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
IntelliJ Idea SpringBoot 數據庫增刪改查實例詳解
SpringBoot 是 SpringMVC 的升級,對于編碼、配置、部署和監(jiān)控,更加簡單。這篇文章主要介紹了IntelliJ Idea SpringBoot 數據庫增刪改查實例,需要的朋友可以參考下2018-02-02
JavaEE中用response向客戶端輸出中文數據亂碼問題分析
這篇文章主要介紹了JavaEE中用response向客戶端輸出中文數據亂碼問題分析,需要的朋友可以參考下2014-10-10

