网站首页 美食营养 游戏数码 手工爱好 生活家居 健康养生 运动户外 职场理财 情感交际 母婴教育 生活知识 知识问答

Mybatis中foreach遍历集合

时间:2026-02-13 11:11:18

1、在mybatis中,如果我们需要查询in集合中的数据,需要使用foreach遍历集合。

<!--新增-->

      <if test="consumList!=null and consumList.size() &gt; 0">

        and oilcard_consum_id in

        <foreach collection="consumList" item="item" 

                 index="index" open="(" separator="," close=")">

          #{item}

        </foreach>

      </if>

Mybatis中foreach遍历集合

2、其中<foreach collection="consumList" item="item"           open="(" separator="," close=")">        #{item}     </foreach>

中的collection标识我们程序传值过来的集合。

Mybatis中foreach遍历集合

3、<foreach collection="consumList" item="item"           open="(" separator="," close=")">        #{item}     </foreach>

标签中的open表示我们遍历的集合以什么字符开始。

Mybatis中foreach遍历集合

4、<foreach collection="consumList" item="item"           open="(" separator="," close=")">        #{item}     </foreach>

标签中的close表示我们遍历的集合以什么字符结尾。

Mybatis中foreach遍历集合

5、<foreach collection="consumList" item="item"           open="(" separator="," close=")">        #{item}     </foreach>

中item是给我们集合遍历取一个变量。

Mybatis中foreach遍历集合

6、我们整个sql可能是如下的语句:

<if test="consumList!=null and consumList.size() &gt; 0">

 and oilcard_consum_id in

 <foreach collection="consumList" item="item"           index="index" open="(" separator="," close=")">

   #{item}

 </foreach></if>

select * from 表名 where oilcard_consum_id in (1,2,3)

Mybatis中foreach遍历集合

© 2026 智德知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com