美文网首页
sql语句返回null时报错的解决方案

sql语句返回null时报错的解决方案

作者: wbpailxt | 来源:发表于2020-01-11 19:19 被阅读0次
int selectCartProductCount(@Param("userId") Integer userId);
  <select id="selectCartProductCount" parameterType="java.lang.Integer" resultType="int">
    select sum(quantity) as count from mmall_cart where user_id = #{userId}
  </select>

这里边有一个隐患,mapper声明方法的时候返回值是int。假如userId是不存在的,那计算sum(quantity)是一个空(null),空是无法赋予基本类型的。
我们要么这样改:

Integer selectCartProductCount(@Param("userId") Integer userId);
  <select id="selectCartProductCount" parameterType="java.lang.Integer" resultType="java.lang.Integer">
    select sum(quantity) as count from mmall_cart where user_id = #{userId}
  </select>

要么处理下sql:

int selectCartProductCount(@Param("userId") Integer userId);
 <select id="selectCartProductCount" parameterType="int" resultType="int">
    select IFNULL(sum(quantity),0) as count from mmall_cart where user_id = #{userId}
  </select>

当sum(quantity)是null的时候,返回0。

相关文章

网友评论

      本文标题:sql语句返回null时报错的解决方案

      本文链接:https://www.haomeiwen.com/subject/hhjbactx.html