1. 程式人生 > >轉載:mybatis踩坑之——foreach迴圈巢狀if判斷

轉載:mybatis踩坑之——foreach迴圈巢狀if判斷

轉載自:作者:超人有點忙
連結:https://www.jianshu.com/p/1ee41604b5da
來源:簡書

今天在修改別人的程式碼bug時,有一個需求是在做匯出excel功能時,mybatis動態構建sql語句的時候,要根據傳進來的map中的一個值來判斷是不是null,從而需要關聯另一張表取得資料。

 1 <select id="getFieldsValue" parameterType="java.util.Map" resultType="java.util.HashMap">
 2         SELECT
 3         <foreach collection
="colList" item="col" index="index" separator=","> 4 <if test="optionList[index] != 'null'"> 5 ${col}.dic_value as ${col} 6 </if> 7 <if test="optionList[index] == 'null'"> 8 9 ${col} 10 </if>
11 </foreach> 12 13 FROM 14 ${tableName} t 15 <foreach collection="optionList" item="option" index="index"> 16 <if test="option != 'null'"> 17 left join t_admin_dic_values ${colList[index]} ON t.${colList[index]}=${colList[index]}.id
18 </if> 19 </foreach> 20 21 WHERE 22 t.id IN 23 <foreach collection="recordList" item="item" separator="," open="(" close=")"> 24 #{item} 25 </foreach> 26 </select>

可以看到SELECT後的<forech>迴圈體是colList,由於我傳進來的是一個Map,這裡的optionList[index]用的是colList迴圈的角標,但是我一度忘記了optionList存的是String,所以我之前的判斷optionList[index] != null" 一直報錯,要加上'null'。

xml檔案 $ 和 # 的區別

1.${}在預編的時候會直接被變數替換,但是存在被注入的問題,表名必須用${},因為#{}在預編的時候會被解析為?佔位符,但當被變數替換的時候會加上 ‘’單引號,表明不允許加單引號(但是反引號``是可以的)



作者:超人有點忙
連結:https://www.jianshu.com/p/1ee41604b5da
來源:簡書