mybatis异常捕获、特殊符号处理、混合入参

异常捕获:
mybatis不鼓励捕捉异常,但在某些特定场景下需要捕捉,这个时候通过try catch是捕捉不到的,mybatis有自己的处理方式,它把异常映射成了DataAccessException,那么我们需要抛出异常并捕捉。 
***Mapper可以throws DataAccessException;


sqlmap中大于、等于、小于符号的处理:
方法一:
<if test="startDate != null and startDate.trim() != ''">
  <![CDATA[ and leave_date >= #{startDate,jdbcType=VARCHAR}]]>
</if>

方法二:用转移字符替换


Caused by: java.lang.NumberFormatException: For input string
原因:mybatis对<if test="index == 'A'">识别错误

修改方法:test="param eq 'A'.toString()"     

或者 <if test="name == &quot;A&quot;">

或者 <if test='name == "A" '>


传入混合参数:
方法一:
Public User selectUser(String name,String area);
<select id="selectUser" resultMap="BaseResultMap">
    select  *  from user_user_t   where user_name = #{0} and user_area= #{1}
</select>


方法二:

Public User selectUser(Map paramMap);
<select id=" selectUser" resultMap="BaseResultMap">
   select  *  from user_user_t   where user_name = #{userName,jdbcType=VARCHAR} and user_area=#{userArea,jdbcType=VARCHAR}
</select>


方法三:
List<Leave> selectByAccounts(@Param("accounts") List<String> accounts, @Param("startDate") String startDate,
                             @Param("endDate") String endDate);
 
where leave_date between #{startDate,jdbcType=VARCHAR} and #{endDate,jdbcType=VARCHAR}
and user_account in
<foreach collection="accounts" item="item" open="(" close=")" separator=",">
  #{item,jdbcType=VARCHAR}
</foreach>

mybaits中使用sum做统计时,如果统计值为0,返回的值不是0而为null,定义mapper时用integer就会报错,此时可以使用函数 COALESCE(number1,number2) 来避免该问题。

例如:COALESCE(sum(amount), 0)   ,当sum的值为null的时候返回0



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值