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

2020-01-11  本文已影响0人  wbpailxt
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。

上一篇 下一篇

猜你喜欢

热点阅读