mybatis 查询sql时foreach使用法

找到俩个例子摘下来

sql查询用户in传list参数

<select id="getEmpsByConditionForeach" resultType="com.test.beans.Employee">
SELECT * FROM tb1_emplyee WHERE id IN
<foreach collection="list" item="item_id" separator="," open="(" close=")">
#{item_id}
</foreach>
</select>

批量插入


<insert id="addEmps">
INSERT INTO tb1_emplyee(last_name,email,gender,d_id)
VALUES
<foreach collection="emps" item="emp" separator=",">
(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
</foreach>
</insert>

collection:指定要遍历的集合:
list类型的参数会特殊处理封装在map中,map的key就叫list
item:将当前遍历出的元素赋值给指定的变量
separator:每个元素之间的分隔符
open:遍历出所有结果拼接一个开始的字符
close:遍历出所有结果拼接一个结束的字符
index:索引。遍历list的时候是index就是索引,item就是当前值
遍历map的时候index表示的就是map的key,item就是map的值
#{变量名}就能取出变量的值也就是当前遍历出的元素

posted @ 2018-12-10 19:37  一心二念  阅读(741)  评论(0编辑  收藏  举报