警惕Mybatis的Foreach的的副作用

来源:互联网 发布:apache maven怎么安装 编辑:程序博客网 时间:2024/05/05 03:38
对于如下SQL:
假设有如下的mapper:
<select id=”testForeach”  parameterType=”map”  resultType=”Student”>    Select * from student    <where>     <choose>        <when test=”ID != null and ID != ‘’ ”>            ID = #{ID}        </when>        <when test=” IDArr != null and IDArr.size()>0”>            And ID IN            <foreach collection="IDArr" open="("                separator="," close=")" item="ID">                ${ID}            </foreach>        </when></choose></where>

当我们传入的IDArr时,最后产生的SQL为:
Select * from student where ID = ‘998’ AND ID IN ( ‘123’, ’234’,…..,’998’)
解决办法:
解决办法有
1) 将红色的ID 换成别的名称,比如“item”。
2) 这两个if 是对同一个字段判断,改为choose… when 结构
<select id=”testForeach”  parameterType=”map”  resultType=”Student”>    Select * from student    <where>     <choose>        <when test=”ID != null and ID != ‘’ ”>            ID = #{ID}        </when>        <when test=” IDArr != null and IDArr.size()>0”>            And ID IN            <foreach collection="IDArr" open="("                separator="," close=")" item="ID">                ${ID}            </foreach>        </when></choose></where>

0 0
原创粉丝点击