mybatis foreach 使用

我这举2个栗子就好。

public int countTemporary(@Param("peq")Map<String, Object> eq ,
@Param("include")Map<String, List<Object>> in);

//这是mapper.java

//传个参数 
`peq`的 map1.put("customer ","张三 "),map1.put("level"1)

    `include` 的  list2.add(7),list2.add(8),list2.add(9),list2.add(10)
    map2.put("status",list2)

上面的 peq 准备使用单层循环,include 就用嵌套循环。

注意:我这2个参数都传的map(不过嵌套的有list)

<select id="countTemporary" resultType="Integer">
        SELECT * 
        FROM `t_sell_contract`
        <where>
        1=1
        <if test="peq != null and peq.size > 0">
                and
                <foreach collection="peq" index="key" item="e" separator="and" >
                    ${key} = #{e}
                </foreach> 
        </if>
        <if test="include != null and include.size > 0">
                and
                <foreach collection="include" index="key" item="e" separator="and" >
                    ${key} in 
                    <foreach collection="e"  item="i" separator="," open="(" close=")">
                    #{i}
                    </foreach> 
                </foreach> 
        </if> 

        </where>
    </select>

到数据库中的sql 就是

SELECT * 
        FROM `t_sell_contract` where 1=1
        and  customer='张三' and level='1'                //这个是pea
        and status in (7,8,9,10)                         // 这个是include

好的。解释一下。

1.foreach 这个 循环的意思
2.collection 字面意思 集合,那就是我们需要循环的对象咯。我用的peq 这只是别名,其实就是代表了我的集合
3.index故名思议,下标。这里值 map《key,value>>中 的 key,比如 我的sql中的 customer 和 level,当然如果你 一 开始传的 是list,那index则指的是 元素的序号
4.separator 分隔的意思。就是你循环一遍后 用什么 来连接下次循环的东西,比如我的 and 和 ,(逗号)。
5.open close 看看我这用的 “()” 就知道 是干嘛用的。循环开始前和结束后添加的东西。

简单易懂。哈赛。佟丽娅卡通! buling buling !

猜你喜欢

转载自blog.csdn.net/alai_programmer/article/details/79537402