【】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()才行!

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