java Mybatis if 标签 字符串判断不生效

问题场景:

看如下sql 你觉得会不会生效

    select
    *
    from institution_balance
    <where>
      <if test="id != null">
        and id = #{id}
      </if>
      <if test="balance == '1'">
        and balance = #{balance}
      </if>
	</where>

结果:

这个代码无论balance传递"1"还是"2",这个都不会生效,会直接略过这个if判断

原因:

因为mybatis是用OGNL表达式来解析的,在OGNL的表达式中,'1’或’2’这种类的都会被解析成字符,而java又是强类型的,字符和单个字符串是不相等的,所以会导致两边的类型不相等,所以标签中的sql不会被解析同个。要想相等,必须两边都是相同的类型。

解决方案

解决方法有三种,分别如下:

1.将单引号换为双引号,把test的引号换成单引号,里面的判断换成双引号即可

    select
    *
    from institution_balance
    <where>
      <if test="id != null">
        and id = #{id}
      </if>
      -- 这里交换了符号顺序  
      <if test='balance == "1"'>
        and balance = #{balance}
      </if>
	</where>

2.使用toString强转,把字符类型使用toString()方法强转为字符串类型

    select
    *
    from institution_balance
    <where>
      <if test="id != null">
        and id = #{id}
      </if>
       -- 这里加了toString()方法
      <if test="balance == '1'.toString()">
        and balance = #{balance}
      </if>
	</where>

3.将字符换成Integer类型,在传递参数时就传递Integer类型,使用Integer类型进行判断

    select
    *
    from institution_balance
    <where>
      <if test="id != null">
        and id = #{id}
      </if>
       -- 这里去掉了单引号
      <if test="balance == 1">
        and balance = #{balance}
      </if>
	</where>

推荐:

推荐使用第一种或者第三种 看着不迷糊简单清楚明了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值