【】mybatis的if判断有坑

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

单个的字符要写到双引号里面才行,改为<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()才行!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章