Double与String类型的数据如何利用mybatis 实现返回

Double与String类型的数据如何利用mybatis 实现返回?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

在使用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,不符合规矩。

报错信息:

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>

看完上述内容,你们掌握Double与String类型的数据如何利用mybatis 实现返回的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!