正文:
1,foreach属性
| 属性 | 是否必选 | 描述 |
| item | 是 | 元素进行迭代时的别名 |
| collection | 是 | 要做迭代的数据集合 |
| separator | 否 | 元素之间的分隔符 |
| open | 否 | 表示该语句以什么开始 |
| close | 否 | 表示该语句以什么结束 |
| index | 否 | 每次迭代到的位置 |
2,select count(1) from user where id in ( ? , ? )
一定要注意到$和#的区别,$的参数直接输出,#的参数会被替换为?,然后传入参数值执行。
<select id="test" resultType="int"> select count(1) from user <where> id in <foreach item="item" collection="list" separator="," open="(" close=")" index=""> #{item.id} </foreach> </where> </select>
3,select count(1) from user where col_a = ? and col_b = ?
<select id="test" resultType="int"> select count(1) from user where <foreach item="item" index="key" collection="map" open="" separator="AND" close=""> ${key} = #{item} </foreach> </select>
4,Oracle :insert into user select ?,? from dual union all select ?,? from dual
<insert id="test"> insert into user (id, name) <foreach collection="userList" item="item" separator="UNION ALL"> select #{item.id}, #{item.name} from user_temp </foreach> </insert>
5,Mysql :insert into user(key, value) values (?, ?) , (?, ?)
<insert id="test"> insert into user(key, value) values <foreach item="item" index="key" collection="map" open="" separator="," close=""> (#{key}, #{item}) </foreach> </insert>
参考博客:
Mybatis foreach 批量操作 - jason5186 - 优快云博客
https://blog.youkuaiyun.com/jason5186/article/details/40896043
本文详细介绍了MyBatis中foreach标签的使用方法,包括其属性如item、collection、separator等,以及如何在SQL语句中应用foreach进行批量操作。通过具体的例子,如批量插入、更新和查询,展示了foreach在不同场景下的应用。
3979

被折叠的 条评论
为什么被折叠?



