Mybatis中foreach的使用

首先我们要明白的是foreach的本质就是把数据库能执行的sql在xml中按照一定语法来进行拼接,所以拼接之前,我们了解一下foreach标签中几个常见元素的作用
1.collection
‌List或Array‌:如果传入的参数类型是List或Array,collection属性的默认值分别是list和array。如果需要自定义集合名称。
‌Map‌:如果传入的参数是Map,collection属性可以指定遍历Map的keys、values或entrySet
2.item
集合遍历中每一个元素的别名
3.open
拼接sql时最前面拼接的字符串
4.separator
拼接sql时候两个元素之间的分隔字符串
5.close
拼接sql时最后面拼接的字符串
6.index
index‌:在List或Array中,index为元素的序号索引;在Map中,index为遍历元素的key值。
举一个简单的例子
一个简单的sql
select * from blog where title is not null and (id=1 or id=2 or id=3)
1.我们使用map集合作为参数实现拼接
<select id="queryBlogForeach" parameterType="map" resultType="blog"> select * from blog <where> title is not null <foreach collection="ids" item="id" open="and (" separator="or" close=")"> id=#{id} </foreach> </where> </select>
2.我们使用list集合作为参数实现拼接
<select id="queryBlogForeach2" parameterType="list" resultType="blog"> select * from blog <where> title is not null <foreach collection="list" item="id" open="and (" separator="or" close=")"> id=#{id} </foreach> </where> </select>

posted @   白小羊  阅读(245)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示