mybatis的 if test 条件判断字符串单双引号解析问题

昨天码代码,掉到坑里,耽误了几个小时才从坑里爬出来-_-|||

由于MyBatis是使用的OGNL表达式,所以

单个的字符要写到双引号里面才行,改为<if test='takeWay == "1"'>或者改为<if test="takeWay == '1'.toString() ">


.xml文件的部分代码

 <insert id="insertDelivery" parameterType="com.zuci.request.DeliveryPreferenceReq" >
      insert cx_customer_deliverypreference
       <trim prefix="(" suffix=")" suffixOverrides="," >
             .... 此处省略
         <if test="takeWay == '1' and workday != null ">
           WORKDAY,
         </if>
         ....
       </trim>

       <trim prefix="values (" suffix=")" suffixOverrides="," >
           .... 此处省略
          <if test="takeWay == '1' and workday != null ">
            #{workday, jdbcType=VARCHAR},
      </if>
      ....
       </trim>   
   </insert>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

takeWay == “1”处出错,导致不执行if判断中的sql,运行程序不报错,没有任何提示。去掉takeWay == “1” and 则可执行。对此我百思不得其解, 
因为自己有写过如下代码,是没错的。

 <if test="messageType == 'senderReceiveSuccess' ">
      ......
 </if>
  • 1
  • 2
  • 3

苦苦纠结了几个小时,最后是我的同事JW大神帮我解决的,膜拜大神o(≧v≦)o~~好棒 
<if test="takeWay == '1' and workday != null "> 
改为<if test='takeWay == "1" and workday != null '> 
或改为<if test="takeWay == '1'.toString() and workday != null ">即可。

原因是:mybatis是用OGNL表达式来解析的,在OGNL的表达式中,’1’会被解析成字符,java是强类型的,char 和 一个string 会导致不等,所以if标签中的sql不会被解析。 

总结下使用方法:单个的字符要写到双引号里面或者使用.toString()才行!

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

补充:转载另一篇博客

在使用 MyBatis if 进行条件判断时,一直报错:

<if test="fwbdh != null and fwbdh == 'BAK'">
    fwbdh=#{fwbdh}
<if>

MyBatis是使用的OGNL表达式来进行解析的,改成:

<if test='fwbdh != null and fwbdh == "BAK"'>
    fwbdh=#{fwbdh}
<if>

同时,MyBatis的if、when里面的test表达式对参数进行判断时,可以调用 java的java.lang.String中定义的方法:

比如:

<if test="fwbdh != null and fwbdh != ''">
	<choose>  
		<when test='fwbdh.indexOf(",") != -1'>  
			AND t.FWBDH  in (${fwbdh}) 
		</when>  
		<otherwise>   
	        	AND t.FWBDH like '%'+#{fwbdh}+'%'  
		</otherwise>  
	</choose> 
</if>

转载自:https://blog.csdn.net/u012780336/article/details/52921043

            https://blog.csdn.net/xxlian1201/article/details/52759349

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值