转载: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
來源:简书

猜你喜欢

转载自www.cnblogs.com/mySummer/p/10142005.html