mybatis 返回Integer,Double,String等类型的数据操作
在使用mybatis的过程中会遇到只返回单独数据类型的问题会用到resultType。
//返回IntegerSELECTspeedfromdws_tfc_state_speed_link_last_rtwherelink_id=#{linkId} //返回Double类型 SELECTtravel_timefromdws_tfc_state_speed_link_last_rtwherelink_id=#{linkId} //返回String类型 SELECTspeedfromdws_tfc_state_speed_link_last_rtwherelink_id=#{linkId}
补充知识:mybatis下返回类型为int,结果为null时报temptedtoreturnnullfromamethodwithaprimitivereturntype(int).
背景了解:
从mysql数据库中查询数据,用Int接收,因为数据库没有数据所以返回null,于是运行时报以下错误,提取关键的信息“attemptedtoreturnnullfromamethodwithaprimitivereturntype(int).”,翻译成中文大概意思是“”尝试从具有基本返回类型(Int)的方法返回null“返回int的方法想要返回null,不符合规矩。
报错信息:
xml中的SQL和报错信息如下:
selectSUM(alert_sum)asalert_sumfromtb_checkresults
2019-06-2717:39:40,742ERROR(DirectJDKLog.java:182)-Servlet.service()forservlet[dispatcherServlet]incontextwithpath[]threwexception[Requestprocessingfailed;nestedexceptionisorg.apache.ibatis.binding.BindingException:Mappermethod'com.chinalife.datacheck.dao.CheckresultDao.getyestodayalertattemptedtoreturnnullfromamethodwithaprimitivereturntype(int).]withrootcauseorg.apache.ibatis.binding.BindingException:Mappermethod'com.chinalife.datacheck.dao.Checkresul*tDao.getyestodayalertattemptedtoreturnnull*********************省略以下那些没用的*********************
解决办法:
(1)利用mysql的函数ifnull
ifnull函数可以判断返回值是否为‘null',不为null时直接返回,为null时返回我们指定的‘0'
selectIFNULL(SUM(alert_sum),0)asalert_sumfromtb_checkresults
(2) 将返回类型改为Integer
int是基本数据类型,默认值是0:integer是int的封装类,是一个类,默认值是null
selectSUM(alert_sum)asalert_sumfromtb_checkresults
找得到,看得懂,明确报错信息很重要。
解决问题有多种办法,符合要求的才是最好的。
以上这篇mybatis返回Integer,Double,String等类型的数据操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。