Mybatis mapper.xml文件中的<foreach></foreach>标签

标签:该标签的作用是遍历集合类型的条件

foreach元素的属性主要有 item,index,collection,open,separator,close。

item表示集合中每一个元素进行迭代时的别名.

    index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置.

    open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符.

    close表示以什么结束

用来循环 collection : 用来指定循环的数据的类型 可以填的值有:array,list,map item

<select id="findUserList" parameterType="UserQueryVo" resultType="UserCustom">
     SELECT * FROM USER
     <where>
        <!-- 使用实现下边的sql拼接: AND (id=1 OR id=10 OR id=16) -->

        <if test="ids!=null and ids.size>0">

           <foreach collection="ids" item="user_id" open="AND (" close=")" separator="or">

                  id=#{user_id}

           </foreach>

       </if>
     </where>
</select>



<!-- 使用实现下边的sql拼接: and id IN(1,10,16)—>

<foreach collection="ids" item="user_id" open="and id IN(" close=")" separator=",">

     #{user_id}

</foreach>
经验分享 程序员 微信小程序 职场和发展